module HashSerializer::Helpers::ClassMethods

Helper methods available on the class

Public Instance Methods

hash_accessor_with_prefix(hash_name, prefix, *keys) click to toggle source

Creates ActiveRecord model methods for a Postgres JSON hash

Example:

>> hash_accessor_with_prefix :stripe_oauth_fields, 'stripe_connect', VALID_STRIPE_OAUTH_FIELDS

@param hash_name [String | Symbol] @param prefix [String] prefix for the generated methods @param keys [Array] array of strings to create methods

# File lib/hash_serializer/helpers.rb, line 39
def hash_accessor_with_prefix(hash_name, prefix, *keys)
  Array(keys).flatten.each do |key|
    prefixed_key = "#{prefix}_#{key}"

    # Ex - billing_token=
    create_setter_methods(hash_name, prefixed_key, key)

    # Ex - billing_token
    create_getters(hash_name, prefixed_key, key)

    # Ex - billing_token_changed?
    create_changed_methods(prefixed_key)
  end
end

Protected Instance Methods

create_changed_methods(prefixed_key) click to toggle source

Creates *_changed? methods referencing the @*_changed property created in create_setter_methods

@param prefixed_key [String] the hash key with the desired prefix

# File lib/hash_serializer/helpers.rb, line 93
def create_changed_methods(prefixed_key)
  create_method("#{prefixed_key}_changed?") do
    instance_variable_get("@#{prefixed_key}_changed") == true
  end
end
create_getters(hash_name, prefixed_key, key) click to toggle source

Creates prefixed getter methods to access the hash value

@param hash_name [String | Symbol] @param prefixed_key [String] the hash key with the desired prefix @param key [String] the non-prefixed hash key

# File lib/hash_serializer/helpers.rb, line 84
def create_getters(hash_name, prefixed_key, key)
  create_method(prefixed_key) do
    send(hash_name)[key]
  end
end
create_setter_methods(hash_name, prefixed_key, key) click to toggle source

Creates setter methods with the prefixed name and adds @*_changed properties, if the value changed, and calls [hash]_will_change! to signify the hash has updated

@param hash_name [String | Symbol] @param prefixed_key [String] the hash key with the desired prefix @param key [String] the non-prefixed hash key

# File lib/hash_serializer/helpers.rb, line 68
def create_setter_methods(hash_name, prefixed_key, key)
  create_method("#{prefixed_key}=") do |value|
    # Set a variable to track whether the value changed
    instance_variable_set("@#{prefixed_key}_changed", true) if send(prefixed_key) != value

    # Store the value
    send(hash_name)[key] = value
    send("#{hash_name}_will_change!") if respond_to? "#{hash_name}_will_change!".to_sym
  end
end

Private Instance Methods

create_method(name, &block) click to toggle source
# File lib/hash_serializer/helpers.rb, line 56
def create_method(name, &block)
  send(:define_method, name, &block)
end