Class: AttrPermit

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_permit.rb,
lib/attr_permit/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source = nil) ⇒ AttrPermit

Returns a new instance of AttrPermit.



35
36
37
38
# File 'lib/attr_permit.rb', line 35

def initialize(source=nil)
  @source = source
  update(source)
end

Class Method Details

.attr_permit(*permissible_methods) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/attr_permit.rb', line 12

def attr_permit(*permissible_methods)
  self.permissible_methods.concat [*permissible_methods, *get_super_attr]
  self.permissible_methods.each do |meth|

    send(:define_method, meth) do
      call_method(meth)
    end

    attr_writer meth unless public_instance_methods.include?("#{meth}=")
  end
end

.permissible_methodsObject



8
9
10
# File 'lib/attr_permit.rb', line 8

def permissible_methods
  @permissible_methods ||= []
end

Instance Method Details

#==(obj) ⇒ Object



79
80
81
# File 'lib/attr_permit.rb', line 79

def ==(obj)
  self.hash == obj.hash
end

#hashObject



83
84
85
# File 'lib/attr_permit.rb', line 83

def hash
  self.to_hash.hash
end

#non_nil_valuesObject



73
74
75
76
77
# File 'lib/attr_permit.rb', line 73

def non_nil_values
  hash = {}
  to_hash.each { |k, v| hash[k] = v unless v.nil? }
  hash
end

#to_enumObject



87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/attr_permit.rb', line 87

def to_enum
  copy = self.dup
  copy.singleton_class.send(:include, Enumerable)

  def copy.each(&block)
    self.class.permissible_methods.each do |item|
      block.call(public_send(item))
    end
  end

  copy
end

#to_hash(big_decimal_as_string: false, all_values_as_string: false) ⇒ Object Also known as: to_h



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/attr_permit.rb', line 56

def to_hash(big_decimal_as_string: false, all_values_as_string: false)
  @big_decimal_as_string = big_decimal_as_string
  @all_values_as_string = all_values_as_string
  hash = {}
  self.class.permissible_methods.each do |var|
    value = send(var)
    value = to_hash_object(value)
    value = big_decimal_as_string_convert(value)
    value = all_values_as_string_convert(value)
    value = array_to_hash(value)
    hash[var] = value
  end
  hash
end

#update(source) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/attr_permit.rb', line 40

def update(source)
  return if source.nil?
  source = OpenStruct.new(source) if source.class <= Hash
  self.class.permissible_methods.each do |meth|
    send("#{meth}=", source.send(meth)) if source.respond_to? meth
  end
end