Sha256: 641ed739ac9ab57fcc0e458e35a2d3c994b406e6e9feb28b39ca6e3f2b1e925c

Contents?: true

Size: 1.17 KB

Versions: 6

Compression:

Stored size: 1.17 KB

Contents

module HungryForm
  module Elements
    module Base
      # This module adds hashing capabilities to form elements.
      # Do not include this module in your classes. It is already
      # included in the base_element class.
      #
      # Sample usage:
      #
      # class MyField
      #   attr_accessor :param1, :param2
      #   hashable :param1, :param2
      #   ...
      # end
      #
      # Any instance of MyField class will have the "to_hash" method
      # that will contain only the accessor/reader params defined in
      # the hashable macro.
      module Hashable
        def self.included(base)
          base.extend ClassMethods
          base.class_attribute :hashable_attributes
          base.hashable_attributes = []
        end

        def to_hash
          hash = self.class.hashable_attributes.each_with_object({}) do |param, h|
            h[param] = send(param) unless send(param).nil?
          end
          hash.merge(_type: self.class.name.demodulize)
        end

        module ClassMethods
          def hashable(*params)
            self.hashable_attributes = hashable_attributes.dup.concat params
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
hungryform-0.0.11 lib/hungryform/elements/base/hashable.rb
hungryform-0.0.10 lib/hungryform/elements/base/hashable.rb
hungryform-0.0.9 lib/hungryform/elements/base/hashable.rb
hungryform-0.0.8 lib/hungryform/elements/base/hashable.rb
hungryform-0.0.7 lib/hungryform/elements/base/hashable.rb
hungryform-0.0.6 lib/hungryform/elements/base/hashable.rb