Skip to content

Instantly share code, notes, and snippets.

@pjb3
Created August 30, 2011 12:21
Show Gist options
  • Select an option

  • Save pjb3/1180775 to your computer and use it in GitHub Desktop.

Select an option

Save pjb3/1180775 to your computer and use it in GitHub Desktop.
DSL for constructing object graph
class DslObject
def initialize(*args, &block)
args.zip(self.class.properties).each do |arg, property|
instance_variable_set("@#{property}", arg)
end
instance_eval(&block) if block
end
def self.properties(*properties)
if properties.empty?
@properties
else
@properties = properties
properties.each do |property|
class_eval %{def #{property}(*args, &block)
@#{property} = args.first unless args.empty?
block ? instance_eval(&block) : @#{property}
end}
end
end
end
def self.has_one(property)
class_eval %{def #{property}(*args, &block)
if !args.empty? || block
@#{property} ||= #{property.to_s.camelize}.new(*args, &block)
end
@#{property}
end}
end
def self.has_many(collection)
class_eval %{attr_reader :#{collection}
def #{collection.to_s.singularize}(*args, &block)
puts "#{collection.to_s.singularize} \#{args.inspect}"
obj = #{collection.to_s.singularize.to_s.classify}.new(*args, &block)
(@#{collection} ||= []) << obj
end}
end
end
@pjb3
Copy link
Author

pjb3 commented Aug 30, 2011

The puts on line 37 makes vim-ruby syntax highlighting sad :(

@pjb3
Copy link
Author

pjb3 commented Aug 30, 2011

Also, Textmate seems to highlight this properly FWIW. As well as Github, obviously :)

@abachman
Copy link

I got correct results by replacing has_many's %{} with %[], fwiw.

http://cl.ly/3L2y1G1e2a0m0D3c0Y2Q

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment