Advertisement
ragmay

Untitled

Sep 27th, 2022
1,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.54 KB | Help | 0 0
  1. module Model
  2.   def self.included(base)
  3.     base.extend(ClassMethods)
  4.   end
  5.  
  6.   def self.my_attr_accessor(*attributes)
  7.     attributes.each do |attribute|
  8.       # Getter
  9.       define_method attribute do
  10.         instance_variable_get "@#{attribute}"
  11.       end
  12.       ########
  13.  
  14.       # Setter
  15.       define_method "#{attribute}=" do |value|
  16.         instance_variable_set "@#{attribute}", value
  17.       end
  18.       ########
  19.     end
  20.   end
  21.  
  22.   my_attr_accessor :id, :title, :body, :created_at, :published
  23.  
  24.   def initialize(params = {})
  25.     @attributes = {}
  26.     params.each do |key, value|
  27.       key = key.to_sym
  28.       @attributes[key] = value
  29.     end
  30.   end
  31.  
  32.   def attributes
  33.     hash = {}
  34.     @attributes.map do |key, value|
  35.       hash[key] = value
  36.     end
  37.     hash
  38.   end
  39.  
  40.   def attributes=(attributes)
  41.     attributes.each do |key, value|
  42.       @attributes[key.to_sym] = value
  43.     end
  44.   end
  45.  
  46.   module ClassMethods
  47.     def attribute(name, *_options)
  48.       case _options[0][:type]
  49.       when :string
  50.         define_method("#{name}=") do
  51.           instance_variable_set "@#{name}", "@#{name}".to_s
  52.         end
  53.       when :integer
  54.         define_method("#{name}=") do
  55.           instance_variable_set "@#{name}", "@#{name}".to_i
  56.         end
  57.       when :boolean
  58.         define_method("#{name}=") do
  59.           instance_variable_set "@#{name}", !!"@#{name}"
  60.         end
  61.       when :datetime
  62.         define_method("#{name}=") do
  63.           instance_variable_set "@#{name}", DateTime.parse("@#{name}")
  64.         end
  65.       end
  66.     end
  67.   end
  68. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement