Class: AssociateJsonb::WithStoreAttribute::InstanceMethodsOnActivation

Inherits:
Module
  • Object
show all
Defined in:
lib/associate_jsonb/with_store_attribute.rb

Instance Method Summary collapse

Constructor Details

#initialize(mixin, store, attribute, key, is_array) ⇒ InstanceMethodsOnActivation

Returns a new instance of InstanceMethodsOnActivation.



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/associate_jsonb/with_store_attribute.rb', line 118

def initialize(mixin, store, attribute, key, is_array)
  is_array = !!(is_array && attribute.to_s =~ /_ids$/)

  array_or_attr = ->(value) {
    is_array \
      ? %Q(Array(#{value}))        : %Q(#{value})
  }

  on_store_change = "_write_attribute(:#{attribute}, #{array_or_attr.call %Q(#{store}["#{key}"])})"
  on_attr_change = "super(#{array_or_attr.call %Q(given)})"

  if is_array
    mixin.class_eval "      def \#{attribute}\n        _read_attribute(:\#{attribute}) || []\n      end\n    CODE\n  end\n\n  mixin.class_eval <<~CODE, __FILE__, __LINE__ + 1\n    def \#{store}=(given)\n      if given.is_a?(::String)\n        given = ActiveSupport::JSON.decode(given) rescue nil\n      end\n\n      if AssociateJsonb.merge_hash?(self.class.attribute_types[\"\#{store}\"])\n        if !given\n          given = {}\n          \#{store}.keys.each do |k|\n            given[k] = nil\n          end\n        end\n        super(\#{store}.deep_merge(given.deep_stringify_keys))\n\n        self.\#{attribute}= \#{store}[\"\#{key}\"] if \#{store}.key?(\"\#{key}\")\n      else\n        super given || {}\n        self.\#{attribute}= \#{store}[\"\#{key}\"]\n      end\n\n      \#{store}\n    end\n\n    def \#{attribute}=(given)\n      \#{on_attr_change}\n      value = \#{store}[\"\#{key}\"] = \#{attribute}.presence\n      \#{store}.delete(\"\#{key}\") unless !value.nil? || AssociateJsonb.merge_hash?(self.class.attribute_types[\"\#{store}\"])\n      value\n    end\n  CODE\nend\n", __FILE__, __LINE__ + 1