Advertisement
ragmay

Untitled

Sep 29th, 2022
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.29 KB | Help | 0 0
  1. # frozen_string_literal: true
  2.  
  3. require 'byebug'
  4. # BEGIN
  5. module Model
  6.   def self.included(base)
  7.     base.extend(ClassMethods)
  8.   end
  9.  
  10.   def initialize(params = {})
  11.     @attributes = {}
  12.     params.each do |key, value|
  13.       key = key.to_sym
  14.       @attributes[key] = value
  15.     end
  16.   end
  17.  
  18.   def attributes
  19.     hash = {}
  20.     @attributes.map do |key, value|
  21.       hash[key] = value
  22.     end
  23.     hash
  24.   end
  25.  
  26.   def attributes=(attributes)
  27.     attributes.each do |key, value|
  28.       @attributes[key.to_sym] = value
  29.     end
  30.   end
  31.  
  32.   module ClassMethods
  33.     def default_values
  34.       @default_values ||= {}
  35.     end
  36.  
  37.     def attributes
  38.       default_values.keys
  39.     end
  40.  
  41.     def attribute(name, value)
  42.       default_values[name] = value
  43.  
  44.       initialize_setter(name, value)
  45.       initialize_getter(name)
  46.     end
  47.  
  48.     def initialize_setter(name, _value)
  49.       byebug if _value[:type] == :datetime
  50.       class_eval <<-SETTING, __FILE__, __LINE__ + 1
  51.         def #{name}=(value)
  52.           @#{name} = value
  53.           @attributes[:#{name}] = @#{name}
  54.         end
  55.       SETTING
  56.     end
  57.  
  58.     def initialize_getter(name)
  59.       class_eval <<-SETTING, __FILE__, __LINE__ + 1
  60.         def #{name}
  61.           @attributes[:#{name}]
  62.         end
  63.       SETTING
  64.     end
  65.   end
  66. end
  67. # END
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement