Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sshaw
Last active August 6, 2017 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sshaw/dbd0f1066f0da2b8407d65fb66285872 to your computer and use it in GitHub Desktop.
Save sshaw/dbd0f1066f0da2b8407d65fb66285872 to your computer and use it in GitHub Desktop.
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