Skip to content

Instantly share code, notes, and snippets.

@rwz
Created September 26, 2014 00:40
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 rwz/ff0ec1d67aa58dd89e6c to your computer and use it in GitHub Desktop.
Save rwz/ff0ec1d67aa58dd89e6c to your computer and use it in GitHub Desktop.
A form-object solution of my wet dreams.

Let's call it AdequateForm for now.

class SignUpForm < AdequateForm
  attribute :first_name
  attribute :last_name
  attribute :birthdate, :date
  
  validates :first_name, :birthdate, presence: true
end

form = SignUpForm.new(first_name: "Pavel")
form.last_name = "Pravosud"
form.attributes # => { first_name: "Pavel", last_name: "Pravosud", birthdate: nil }
form.valid? # => false
form.errors # => <ActiveModel::Errors {:birthdate=>["can't be blank"]}>
form.assign_attributes "birthdate(1i)" => "1986", "birthdate(2i)" => "8", "birthdate(3i)" => "25"
form.birthdate # => Mon, 25 Aug 1986
form.valid? # => true
form.update(first_name: nil) # => false, because invalid
form.update(first_name: "Pavel") # => true, all good

Also, some goodies:

class SomeOtherForm < AdequateForm
  # copying attributes/validation data from AR models
  copy_attributes_from Post
  copy_validations_from Post
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment