Project

loose_attr

0.0
Repository is archived
No commit activity in last 3 years
No release in over 3 years
loose_attr
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.10
>= 0
~> 10.0
>= 0
~> 1.0

Runtime

< 5.0, > 3.0
>= 0
 Project Readme

LooseAttr

MIT License Circle CI Code Climate Test Coverage

Overview

LooseAttr is ActiveRecord extension module. for the element (column) as defined in the JSON format, can property access.

Installation

Add this line to your application's Gemfile:

gem 'loose_attr'

Usage

Normal

Step1. To prepare the ext_field column. Put the data in JSON format to ext_field.

class CreateAllTables < ActiveRecord::Migration
  def self.up
    create_table(:posts) do |t|
      t.string  :body
      t.string  :category
      t.boolean :actived
      t.text    :ext_field
    end
  end
end

Step2. To define the loose_attr the Model class of ActiceReocrd.

class Post < ActiveRecord::Base
  loose_attr :comment_count,   default_value: 1
  loose_attr :user_name,       default_value: 'noname'
  loose_attr(
    :posted_at,
    cast_type: :date,
    default_value: '2016-01-01 00:00:00',
    option: { format: '%Y-%m-%d %H:%M:%S' }
  )
end

Step3. Call the property defined in loose_attr.

Post.create(
  id: 1,
  body: 'hogefoobar',
  category: :it,
  actived: true,
  ext_field: {
    comment_count: 10,
    user_name: nil,
    posted_at: nil
  }.to_json
)

post = Post.find(1)
puts post.body # hogefoobar
puts post.comment_count # 10
puts post.user_name # noname
puts post.posted_at # 2016-01-01 00:00:00

Extra

If you want to ext_field to ext when, define the modify_loose_attr_column_name.

class CreateAllTables < ActiveRecord::Migration
  def self.up
    create_table(:posts) do |t|
      t.string  :body
      t.string  :category
      t.boolean :actived
      t.text    :ext
    end
  end
end

class Post < ActiveRecord::Base
  modify_loose_attr_column_name 'ext'
  loose_attr :comment_count,   default_value: 1
  loose_attr :user_name,       default_value: 'noname'
  loose_attr(
    :posted_at,
    cast_type: :date,
    default_value: '2016-01-01 00:00:00',
    option: { format: '%Y-%m-%d %H:%M:%S' }
  )
end

loose_attr option property

Propety Required Default Remarks
default_value × - hoge
cast_type × - integer OR string OR boolean OR date
option:format × - cast_type = date only

License

The gem is available as open source under the terms of the MIT License.