Skip to content

Instantly share code, notes, and snippets.

@matthuhiggins
Created July 12, 2013 00:12
Show Gist options
  • Save matthuhiggins/5980387 to your computer and use it in GitHub Desktop.
Save matthuhiggins/5980387 to your computer and use it in GitHub Desktop.
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