Module: Gadgeto::Dslable::ClassMethods

Defined in:
lib/gadgeto/dslable.rb

Instance Method Summary collapse

Instance Method Details

#dslable_method(method, *args) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/gadgeto/dslable.rb', line 72

def dslable_method(method, *args)
  self.instance_eval do

    stored_at = method.to_s + 's' # pluralize with ActiveSupport

    # method_params:          key, *arguments, options = {}
    # method_values_set:      i.name = name
    # method_setters_getters: def key, def arguments, def options

    method_params, method_values_set, method_accessors = [], [], []

    args.each do |arg|
      unless [String, Symbol, Hash].include? arg.class
        raise ArgumentError, 'allowed arguments are Symbols, Strings and Hashes'
      end

      method_params          << (arg.is_a?(Hash) ? arg.to_a : [arg]).flatten.join(' = ')

      arg_name = (arg.is_a?(Hash) ? arg.keys.first : arg).to_s.gsub('*', '')

      method_values_set      << arg_name
      method_accessors       << arg_name
    end

    method_params = method_params.join(', ')

    method_values_set = method_values_set.map do |p|
      'i.%s = %s' % [p, p]
    end.join(';')

    method_accessors = method_accessors.map do |p|
      "def #{p}; read_attribute(:#{p}); end;" + "def #{p}=(v); write_attribute(:#{p}, v); end;"
    end.join

    self.class_eval "\n\#{method_accessors}\n\ndef draw(code = nil, &block)\ni = self.class.new\n\nif code\ni.instance_eval code\nelse\ni.instance_eval &block\nend\n\n@\#{stored_at} = i.\#{stored_at}\nreturn nil\nend\n\ndef \#{method.to_s}(\#{method_params}, &block)\ni = self.class.new\n\#{method_values_set}\n\ni.instance_eval &block if block\n\nself.\#{stored_at} << i\nend\n\ndef \#{stored_at}\n@\#{stored_at} ||= []\nend\n\ndef \#{stored_at}=(v)\n@\#{stored_at} = v\nend\n\ndef attributes\n@attributes ||= {}\nend\n\ndef attributes=(a)\n@attributes = a\nend\n\ndef read_attribute(n)\nattributes[n]\nend\n\ndef write_attribute(n, v)\nattributes[n] = v\nend\n\n"

  end
end