ActiveRecord helper to specify attributes that are stored as strings but consumed as symbols.
Ruby
Switch branches/tags
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
test
.document
.gitignore
.rvmrc
Gemfile
Gemfile.lock
LICENSE
README.rdoc
Rakefile
VERSION
attr_symbol.gemspec

README.rdoc

attr_symbol

Allows you to declare attributes that are handled as symbols. Assigning a value to the attribute converts it to a symbol, and accessing the attribute always returns a symbol.

When used in an ActiveRecord model class, the attribute will be stored as a string in the underlying database column.

Usage in Plain Ol' Ruby Objects

class User
    attr_symbol :state

    def initialize
        @state = :inactive
    end
end

u = User.new
p u.state # => :inactive

u.state = 'active'
p u.state # => :active

u.state = "    \r  \n\r  \n \n  inactive \n\r  \n\r    foo filler \r <html lang=\"en\"></html> \r\n \n\n   "
p u.state # => :inactive

Usage with ActiveRecord

class Thing < ActiveRecord::Base
  attr_symbol :a
end

# Stores the string 'foo' in the field 'a'
thing = Thing.create!(:a => :foo)

thing = Thing.find(1)
thing.a --> :foo

thing.a = 'urk'
thing.a --> :urk

thing.a = ''
thing.a --> nil

thing.a = '  '
thing.a --> nil

Copyright

Copyright © 2012 Justin Wienckowski. Freely distributable under the MIT License. See LICENSE for details.