Создайте файл app_config.yml
в каталоге config
.
page:
small: 10
medium: 20
large: 30
sort:
name: name DESC
amount: amount ASC
date: created_at DESC
Создать UserOptions
класс в каталоге моделей.
class UserOptions
def self.page_option key
options['page'][key] rescue nil
end
def self.sort_option key
options['sort'][key] rescue nil
end
def self.options
@options ||= YAML.load_file( File.join(RAILS_ROOT,
"config", "app_config.yml")) rescue {}
end
# use this in the view to set the preference
def self.page_collection
option_collection 'page'
end
# use this in the view to set the preference
def self.sort_collection
option_collection 'sort'
end
def self.option_collection key
(options[key]|| {}).to_a
end
end
Настройте ваши модели:
class User
has_one :preference
end
class Preference
def sort_preference(default = nil)
UserOptions.sort_option(attributes['sort_preference']) || default
end
def per_page_preference(default = nil)
UserOptions.page_option(attributes['per_page_preference']) || default
end
end
Теперь вы можете делать следующее:
current_user.preference.per_page_preference
# use 10 as the page size if no value is given
current_user.preference.per_page_preference(10)