Created
December 16, 2013 21:57
-
-
Save elight/7995141 to your computer and use it in GitHub Desktop.
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
def attribute(name, options = {}) | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name} | |
attributes[:#{name}] | |
end | |
EOS | |
case options[:type] | |
when :boolean | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = case new_#{name} | |
when true,'true' | |
true | |
when false,'false' | |
false | |
end | |
end | |
EOS | |
when :float | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = new_#{name}.to_f | |
end | |
EOS | |
when :integer | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = new_#{name}.to_i | |
end | |
EOS | |
when :string | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = new_#{name}.to_s | |
end | |
EOS | |
when :time | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = if new_#{name}.nil? || new_#{name} == "" || new_#{name}.is_a?(Time) | |
new_#{name} | |
else | |
Time.parse(new_#{name}) | |
end | |
end | |
EOS | |
when :array | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = [*new_#{name}] | |
end | |
EOS | |
else | |
if squash = options[:squash] | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_data) | |
if new_data.is_a?(Hash) | |
if new_data.has_key?(:'#{squash}') | |
attributes[:#{name}] = new_data[:'#{squash}'] | |
elsif new_data.has_key?("#{squash}") | |
attributes[:#{name}] = new_data["#{squash}"] | |
else | |
attributes[:#{name}] = [ new_data ] | |
end | |
else | |
attributes[:#{name}] = new_data | |
end | |
end | |
EOS | |
else | |
class_eval <<-EOS, __FILE__, __LINE__ | |
def #{name}=(new_#{name}) | |
attributes[:#{name}] = new_#{name} | |
end | |
EOS | |
end | |
end | |
@attributes ||= [] | |
@attributes |= [name] | |
for new_alias in [*options[:aliases]] | |
aliases[new_alias] = name | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment