Created
August 30, 2011 12:21
-
-
Save pjb3/1180775 to your computer and use it in GitHub Desktop.
DSL for constructing object graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
I got correct results by replacing has_many's %{} with %[], fwiw.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, Textmate seems to highlight this properly FWIW. As well as Github, obviously :)