StaticRecord
Create models with static data provided by YAML file stored locally, is useful for models like categories to store data without have to access to database. Is based on ActiveRecord and it permits relations with native models.
Installation
Add this line to your application's Gemfile:
gem 'static_record'
And then execute:
$ bundle
Or install it yourself as:
$ gem install static_record
Usage
You can create your own static model creating a ruby file in app/models. Remember name your model according to the rails convention.
This is an example of static model for categories
# app/models/category.rb
class Category < StaticRecord::Base
end
Or if you have your model static data in a custom directory, you can select it.
# app/models/category.rb
class Category < StaticRecord::Base
file '/path/to/file.yml'
end
Also you have to create the model data in db/static, the name of the YAML file is by default the name of the table for model. In other words, if your model name is category, you'll have to name your data file as categories.yml. You can see the rails convention here.
# db/static/categories.yml
---
- id: 1
code: 84335d3f-18b8-4934-b1d2-92e2d5228684
name: Vehicles and Planes
- id: 2
code: c4785f56-0a24-4405-9832-0092c7fd21d9
name: Dogs and Cats
- id: 3
code: 8f0be8ed-5cf2-4170-8c96-207dc0193c9a
name: Babies
- id: 4
code: 2974eec1-54ad-4ed5-8f21-af8bc0d5b473
name: Technology
# ...
Use the model like an ActiveRecord model, some functionalities doesn't work because it's a static model, but the main functionalities are the same.
# Get all categories
Category.all
# Find category 4 (Technology)
Category.find 4
# Find category 4 (Technology) and 1 (Vehicles and Planes)
Category.find 4, 1
Use find_by or find_by! like ActionRecord.
# Find by attribute without throwing an error.
Category.find_by name: 'Is not stored'
# => []
# Find by attribute without throwing an error.
Category.find_by! name: 'Is not stored'
# =>
# StaticRecord::RecordNotFound: Couldn't find categories like name as Is not
# stored
# Also you can use dynamic methods.
Category.find_by_name 'Is not stored'
# => []
Use array methods it's possible too.
Category.all
Category.first
Category.second
Category.last
Category.count
# Etc...
Contributing
If you want to contribute with the project, you can fork this repo and create a pull request with your features or fixes. The code is written using the ruby style guide. Read this article before contribute to this project.
Also you can follow me on Twitter @molayab_.
License
The gem is available as open source under the terms of the MIT License.