Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

[PATCH] Allow classes using validation to specify how attributes should be read

#2936

This patch adds a hook method to validations allowing a class to define how it's attributes should be acquired. This is useful should the class not use the default of having a method for each attribute and instead store values in a hash e.g.

class MyClass
  include ActiveModel::Validations

  def initialize(data = {})
    @data = data
  end
  
  def []=(key, value)
    @data[key] = value
  end

  private
  
  def value_for(key)
    @data[key]
  end
end

By overriding the value_for method you have control over how attribute values are retrieved.

As Rails 3 is all about not having to hack the framework and instead provide hooks I believe this is a great addition an have use-cases right away.

Reported by Jamie Hill · July 22nd, 2009 @ 01:21 AM

State: resolved
Milestone: 3.0.2
Assigned to: josh josh
Importance: none

Activity

  1. Jamie Hill
    Jamie Hill
    • Assigned user set to Yehuda Katz (wycats)

    July 22nd, 2009 @ 10:50 AM

  2. Jamie Hill
    Jamie Hill
    • Title changed from Allow classes using validation to specify how attributes should be read to [PATCH] Allow classes using validation to specify how attributes should be read

    July 22nd, 2009 @ 12:33 PM

  3. darkliquid
    darkliquid

    +1

    This certainly makes reuse of the Validation system in isolation from the rest of the rails framework a little easier since you don't have the restriction of having to define a public reader for every attribute you want to validate.

    July 27th, 2009 @ 12:04 PM

  4. Michael Koziarski
    Michael Koziarski
    • Assigned user changed from Yehuda Katz (wycats) to josh
    • Milestone cleared.

    Josh is working in this area now

    August 3rd, 2009 @ 06:03 AM

  5. josh
    josh
    • State changed from new to open

    August 3rd, 2009 @ 08:15 PM

  6. josh
    josh

    value_for is too generic. Maybe read_attribute_for_validation.

    August 5th, 2009 @ 03:22 PM

  7. Jamie Hill
    Jamie Hill

    Thanks for getting back to me on this.

    Agreed on the name, new patch attached.

    August 5th, 2009 @ 05:15 PM

  8. Repository
  9. Jeremy Kemper
    Jeremy Kemper
    • Milestone set to 3.0.2
    • Importance changed from to

    October 15th, 2010 @ 11:01 PM