Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Model
- def self.included(base)
- base.extend(ClassMethods)
- end
- def self.my_attr_accessor(*attributes)
- attributes.each do |attribute|
- # Getter
- define_method attribute do
- instance_variable_get "@#{attribute}"
- end
- ########
- # Setter
- define_method "#{attribute}=" do |value|
- instance_variable_set "@#{attribute}", value
- end
- ########
- end
- end
- my_attr_accessor :id, :title, :body, :created_at, :published
- def initialize(params = {})
- @attributes = {}
- params.each do |key, value|
- key = key.to_sym
- @attributes[key] = value
- end
- end
- def attributes
- hash = {}
- @attributes.map do |key, value|
- hash[key] = value
- end
- hash
- end
- def attributes=(attributes)
- attributes.each do |key, value|
- @attributes[key.to_sym] = value
- end
- end
- module ClassMethods
- def attribute(name, *_options)
- case _options[0][:type]
- when :string
- define_method("#{name}=") do
- instance_variable_set "@#{name}", "@#{name}".to_s
- end
- when :integer
- define_method("#{name}=") do
- instance_variable_set "@#{name}", "@#{name}".to_i
- end
- when :boolean
- define_method("#{name}=") do
- instance_variable_set "@#{name}", !!"@#{name}"
- end
- when :datetime
- define_method("#{name}=") do
- instance_variable_set "@#{name}", DateTime.parse("@#{name}")
- end
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement