Skip to content

Getting length of string properties #244

Closed
crantok opened this Issue Mar 21, 2013 · 2 comments

2 participants

@crantok
crantok commented Mar 21, 2013

I want to get the defined length limit for any given String property in a DataMapper model. I want to use this information to enforce max length in html text inputs so that the user is prevented from entering text that is too long to save.

This is my implementation. Apart from making it generic to any property option (which I assume would be the next logical step) I would appreciate any guidance on whether this would be better done in another way.

module DataMapper
  module Resource
    def length_of_property name
      begin
        properties.select { |x| x.name == name }.first.length
      rescue
        raise "Either property #{self.class.name}##{name} is unknown or it does not have a :length option."
      end
    end
  end
end

which allows me to do e.g.

User.get(1).length_of_property :email
@namelessjon
DataMapper member

Properties has a hash-like interface, but is ordered, so

User.get(1).class.properties[:email].length

will work. Or you can use User.get(1).properties... as you've been doing (The properties instance method is technically private api, but is probably stable)

@crantok
crantok commented Mar 21, 2013

That's much better. Thanks!

I think I may just end up using

User.properties[:email].length
@crantok crantok closed this Mar 21, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.