Skip to content

Instantly share code, notes, and snippets.

@sshaw sshaw/form_fields.rb
Last active Aug 6, 2017

Embed
What would you like to do?
Ruby module to help create classes for form parameters (or other things). Also see Class2: https://github.com/sshaw/class2
module FormFields
def self.included(klass)
klass.class_eval do
def self.fields(*args)
args.flatten!
attr_accessor(*args)
@@fields = args.map(&:to_sym)
end
end
end
def initialize(hash = nil)
(hash || {}).each do |name, value|
next unless @@fields.include?(name) || name.respond_to?(:to_sym) && @@fields.include?(name.to_sym)
public_send("#{name}=", value)
end
end
def to_h
@@fields.each_with_object({}) { |name, h| h[name] = public_send(name) }
end
end
class SomeForm
include FormFields
include ActiveModel::Validations
fields :foo, :bar, :baz
validates :foo, :presence => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.