Module: HashSerializer::Helpers
- Defined in:
- lib/hash_serializer/helpers.rb
Overview
Helper methods for generating methods from hash keys and validating keys
Instance Method Summary collapse
-
#hash_accessor_with_prefix(hash, prefix, *keys) ⇒ Object
Creates ActiveRecord model methods for a Postgres JSON hash.
-
#validate_hash_serializer_keys(hash_name, valid_keys) ⇒ Array
Validates a Postgres JSON hash on an ActiveRecord model does not include extra keys.
Instance Method Details
#hash_accessor_with_prefix(hash, prefix, *keys) ⇒ Object
Creates ActiveRecord model methods for a Postgres JSON hash
Example:
>> store_accessor_with_prefix :stripe_oauth_fields, 'stripe_connect', VALID_STRIPE_OAUTH_FIELDS
31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/hash_serializer/helpers.rb', line 31 def hash_accessor_with_prefix(hash, prefix, *keys) Array(keys).flatten.each do |key| prefixed_key = "#{prefix}_#{key}" # Ex - billing_token= create_setter_methods(hash, prefixed_key, key) # Ex - billing_token create_getters(hash, prefixed_key, key) # Ex - billing_token_changed? create_changed_methods(prefixed_key) end end |
#validate_hash_serializer_keys(hash_name, valid_keys) ⇒ Array
Validates a Postgres JSON hash on an ActiveRecord model does not include extra keys. It prevents user created data on JSON column types.
Example:
>> validate_hash_serializer :billing_hash, %w(name address city state)
14 15 16 17 18 19 20 21 |
# File 'lib/hash_serializer/helpers.rb', line 14 def validate_hash_serializer_keys(hash_name, valid_keys) return if send(hash_name).nil? # || !send("#{hash_name}_changed?") invalid_keys = send(hash_name).keys.map(&:to_s) - valid_keys.map(&:to_s) return if invalid_keys.empty? invalid_keys.sort end |