Statics
Base class and modules for static models.
Links:
Requirements
Installation
To install, run:
gem install statics
Or add the following to your Gemfile:
gem "statics"
Usage
Setting the data path:
Statics.configure do |config|
config.data_path = "data/"
end
Defining a static model:
class Post < Statics::Model
filename "posts"
attribute :title, Types::Strict::String
end
# data/posts.yml
---
post1:
title: "Post 1"
post2:
title: "Post 2"
Post.all
#=> #<Statics::Collection records=[#<Post key=:post1 title="Post 1">, #<Post key=:post2 title="Post 2">]>
Post.where(title: "Post 1")
#=> #<Statics::Collection records=[#<Post key=:post1 title="Post 1">]>
Post.where_not(title: "Post 1")
#=> #<Statics::Collection records=[#<Post key=:post2 title="Post 2">]>
Post.find_by(key: :post1)
#=> #<Post key=:post1 title="Post 1">
Post[:post1]
#=> #<Post key=:post1 title="Post 1">
Post.pluck(:title)
#=> ["Post 1", "Post 2"]
post = Post.first
#=> #<Post key=:post1 title="Post 1">
post.key
#=> :post1
post.title
#=> "Post 1"
post.attributes
#=> {:title=>"Post 1", :key=>:post1}
Defining translatable attributes:
class Post < Statics::Model
include Statics::Translatable
filename "posts"
attribute :title, Types::Strict::String
translatable_attribute :body
end
# data/posts.yml
---
post1:
title: "Post 1"
body:
en: "Hello!"
nl: "Hallo!"
post2:
title: "Post 2"
body:
en: "Bye!"
nl: "Doei!"
post = Post.first
# when I18n.locale is :en
post.body #=> "Hello!"
post.body(locale: :nl) #=> "Hallo!"
Defining omittable attributes with defaults:
class Post < Statics::Model
include Statics::Translatable
filename "posts"
attribute :title, Types::Strict::String
# With default
attribute? :author, Types::Strict::String.default("Unknown")
# Without default
# attribute? :author, Types::Strict::String
end
# data/posts.yml
---
post1:
title: "Post 1"
author: "Rick Sanchez"
post2:
title: "Post 2"
post1 = Post.first
post1. #=> "Rick Sanchez"
post2 = Post.last
post2. #=> "Unknown"
Check dry-types for documentation about the built-in types.
Caveats
If you have dates in your yaml-files, use the following format for them to be handled properly: YYYY-MM-DD
Tests
To test, run:
bundle exec rspec spec/
Versioning
Read Semantic Versioning for details. Briefly, it means:
- Major (X.y.z) - Incremented for any backwards incompatible public API changes.
- Minor (x.Y.z) - Incremented for new, backwards compatible, public API enhancements/fixes.
- Patch (x.y.Z) - Incremented for small, backwards compatible, bug fixes.
License
Copyright 2018 Pablo Crivella. Read LICENSE for details.