Last active
December 15, 2015 00:38
-
-
Save msalvadores/5174299 to your computer and use it in GitHub Desktop.
A mini DSL to dynamically generate objects in Ruby.
This file contains 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
require 'pry' | |
module Test | |
module Settings | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
attr_accessor :settings | |
def define_attribute(attr) | |
define_method "#{attr}=" do |*splat| | |
self.attributes[attr] = splat.first | |
end | |
define_method "#{attr}" do |*splat| | |
return self.attributes[attr] | |
end | |
end | |
end | |
end | |
class Resource | |
include Settings | |
attr_reader :attributes | |
def initialize() | |
@attributes = Hash.new | |
end | |
end | |
class SomeModel < Resource | |
define_attribute :some | |
end | |
end | |
inst = Test::SomeModel.new | |
inst.some= "a" | |
puts inst.some | |
puts inst.attributes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment