Skip to content

Instantly share code, notes, and snippets.

@westonganger
Last active October 11, 2023 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westonganger/fb54259e7e794cff055554b58e8cf397 to your computer and use it in GitHub Desktop.
Save westonganger/fb54259e7e794cff055554b58e8cf397 to your computer and use it in GitHub Desktop.
Simple Rails Form Objects
class Forms::BaseForm
include ActiveModel::Validations
def initialize(attrs={})
attrs ||= {}
attrs.each do |k,v|
self.send("#{k}=", v) ### Use send so that it checks that attr_accessor has already defined the method so its a valid attribute
end
end
def to_key
nil
end
def model_name
sanitized_class_name = self.class.name.to_s.gsub("Forms::", '').gsub(/Form$/, '')
ActiveModel::Name.new(self, self.class.superclass, sanitized_class_name)
end
end
class Forms::ExampleForm < Forms::Base
attr_accessor :app_id, :file
validates :app_id, presence: {message: "Must select an App"}
validates :file, presence: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment