I'm using Virtus to create models that represent Salesforce objects.
I'm trying to create attributes that have friendly names that are used to access the value and method that I can use to retrieve a identifier "String" for that variable.
Object.attribute #=> "BOB"
Object.get_identifier(:attribute_name) #=> "KEY"
# OR something like this
Object.attribute.identifier #=> "KEY"
The friendly name is used as the getter/setter and a identifier that I can store each attribute corresponding to the API name.
Here is an example:
class Case
include Virtus.model
attribute :case_number, String, identifier: 'Case_Number__c'
end
c = Case.new(case_number: 'XXX')
c.case_number #=> 'XXX'
c.case_number.identifier #=> 'Case_Number__c'
Or, instead of having a method on the Attribute itself, maybe a secondary method gets created for each identifier set:
c.case_number #=> 'XXX'
c.case_number_identifier #=> 'Case_Number__c'
Could I extend Virtus::Attribute and add this? If so, I'm unsure on how to go about it.
Monkey patching Virtus'
Attributeclass certainly is an option.However, reaching into the internals of a library makes you vulnerable to refactorings in the private part of that libraries' source code.
Instead, you could use a helper module that encapsulates this feature. Here is a suggestion how:
You don't need Virtus in order to implement your API identifiers. A similar helper module could just register
attr_accessors instead of Virtus attributes.However, Virtus has other handy features like the hash constructors and attribute coersion. If you don't mind living without these features or finding replacements, ditching Virtus should not be a problem.
HTH! :)