Created
July 12, 2013 00:12
-
-
Save matthuhiggins/5980387 to your computer and use it in GitHub Desktop.
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
module ActiveModel | |
module Typecasting | |
extend ActiveSupport::Concern | |
# | |
# class PoopFactory | |
# include ActiveModel::Model | |
# include ActiveModel::Typecasting | |
# | |
# typecast_accessor :color, type: :string | |
# typecast_accessor :price, type: :integer | |
# end | |
# | |
module ClassMethods | |
TRUE_VALS = [true, 'true', '1'] | |
TYPECASTERS = { | |
boolean: -> value { TRUE_VALS.include?(value) }, | |
float: -> value { value.to_f }, | |
integer: -> value { value.to_i }, | |
string: -> value { value.to_s }, | |
time: -> value { Time.parse(value) } | |
} | |
def typecast_accessors(attributes) | |
attributes.each do |key, options| | |
typecasted_attribute key, options | |
end | |
end | |
def typecast_accessor(name, options = {}) | |
define_method name do | |
instance_variable_get("@#{name}") | |
end | |
define_method "#{name}=" do |value| | |
instance_variable_set("@#{name}", value) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment