Last active
October 11, 2023 18:23
-
-
Save westonganger/fb54259e7e794cff055554b58e8cf397 to your computer and use it in GitHub Desktop.
Simple Rails Form Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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