0

consider the following example

module DataMapper
  class Property
    class CustomType < DataMapper::Property::Text

      def load(value)
        # do stuff and return formatted value 
      end
    end  
  end
end

Class A
  property :name, String
  property :value, CustomType
end

now when I do A.first or A.first.value the load method gets executed, but the calculations that I need to do inside load is dependent on that instance's name property. So how do I get the context of this instance/resource(as referred inside source code) inside the load method ?

Please let me know if the question is not clear yet !

Mudassir Ali
  • 7,913
  • 4
  • 32
  • 60

1 Answers1

0

You are attempting to break encapsulation. The name and value are different properties, and thus each should be in ignorance of the other's existence, let alone value.

The correct solution is to move the "stuff" to an object which has visibility over both properties. The two options are:

  1. the A class (as suggested by user1376019); or
  2. a complex data type, e.g. NameAndValue < DataMapper::Property::Object, which encapsulates both properties.

If you need to perform aggregate functions over the individual properties, the second option would not work, unless you can somehow override the complex property to have multiple fields.

In either case, value cannot refer to name without a reference to it.

Community
  • 1
  • 1
Matty K
  • 3,781
  • 2
  • 22
  • 19