Sha256: 254b0499d6eba353b9846c388266f79fc1bd5ffc24c288fe6872eb47efb362c7

Contents?: true

Size: 1.2 KB

Versions: 4

Compression:

Stored size: 1.2 KB

Contents

require 'json'

module SlayerRails
  module Extensions
    module Form
      extend ActiveSupport::Concern

      included do
        include ActiveModel::Model

        def validate!
          raise Slayer::FormValidationError, errors unless valid?
        end

        class << self
          def from_params(params, additional_params: {}, root_key: nil)
            params     = params.respond_to?(:to_unsafe_h) ? params.to_unsafe_h : params.to_h
            params     = params.deep_symbolize_keys
            attr_names = attribute_set.map(&:name)

            params = params.fetch(root_key, {}) if root_key.present?

            attr_hash = params
                        .merge(params.slice(*attr_names))
                        .merge(additional_params)

            new(attr_hash)
          end

          def from_model(model)
            attr_hash = attribute_set.map(&:name)
                        .select { |attr_name| model.respond_to?(attr_name) }
                        .map    { |attr_name| [attr_name, model.public_send(attr_name)] }

            new(attr_hash.to_h)
          end

          def from_json(json)
            from_params(JSON.parse(json))
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
slayer_rails-0.3.3 lib/slayer_rails/extensions/form.rb
slayer_rails-0.3.2 lib/slayer_rails/extensions/form.rb
slayer_rails-0.3.1 lib/slayer_rails/extensions/form.rb
slayer_rails-0.3.0 lib/slayer_rails/extensions/form.rb