easy_model
EasyModel provides features of database independent attribute. You can define the attribute like ActiveRecord that perform data conversion during assignment.
Define database independent attribute
First, include EasyModel to your model. Next define attribute by ‘column` method.
class LoginForm
include EasyModel::Column
column :member_no, :integer
column :password, :string
column :remember, :boolan, default: false
end
When you assign a value to attribute defined by ‘column` method, a value is converted to attribute’s data type (like ActiveRecord).
login_form = LoginForm.new(:member_no => '1234567',
:password => 'PASSWORD',
:remember => 'false')
login_form.member_no # => 1234567
login_form.member_no_before_type_cast # => '1234567'
login_form.password # => 'PASSWORD'
login_form.password_before_type_cast # => 'PASSWORD'
login_form.remember # => false
login_form.remember_before_type_cast # => 'false'
Internationalization
EasyModel uses I18n to internationalization. By default, the look up key is ‘<locale>.easy_model`.
en:
easy_model:
models:
login_form: Login form
attributes:
login_form:
member_no: Member number
password: Password
remember: Keep the login state.
By define the ‘i18n_scope` method, you can change the look up key. For example, to use the look up key same as ActiveRecord:
class LoginForm
include EasyModel::Column
def self.i18n_scope
:activerecord
end
end
Search form
EasyModel::SearchForm is useful to create search form model. EasyModel::SearchForm includes EasyModel::Column, and provides useful features to searching. Only define the ‘scoped` method, you can use query method same as ActiveRecord.
For example:
class UserSearchForm < EasyModel::SearchForm
column :name, :string
column :status, :integer
validates :status, :inclusion => [1, 2, 3]
def scoped
scoped = User.all
# Add to conditions if value is present.
scoped = scoped.where(:name => name) if self.name.present?
scoped = scoped.where(:status => status) if self.status.present?
# Return scope including search conditions.
scoped
end
end
Query methods (i.e. find, all, …) is delegated to ‘scoped` method. So, you can use the interface same as ActiveRecord::Relation.
user_search_form = UserSearchForm.new(params[:user_search_form])
if user_search_form.valid?
users = user_search_form.all
else
...
end
Copyright
Copyright © 2012 Synergy Marketing, Inc. See LICENSE.txt for further details.