palkan/store_attribute

Add support for :default option

Closed this issue · 6 comments

Does it make sense to add support for :default option on top of set of typecasting options?

I think, it makes sense.

Though it's not clear how exactly we want it to work. For example:

class Product < ActiveRecord::Base
   store_attribute :settings, :color, :string, default: "red"
end

How this should work?

  • accessor returns the default value (seems reasonable)
Product.new.color #=> "red"
  • should store attribute contain the default?
Product.new.settings #=> ? should this be `{ "color" => "red"}` or `{}`?
  • should we persist the default value on save?
Product.new.save!
#=> INSERT INTO products (settings) values ('{"color":"red"}'); ???

How this should work?

  • accessor returns the default value (seems reasonable)
Product.new.color #=> "red"
  • should store attribute contain the default?
Product.new.settings #=> ? should this be `{ "color" => "red"}` or `{}`?
  • should we persist the default value on save?
Product.new.save!
#=> INSERT INTO products (settings) values ('{"color":"red"}'); ???

I think that behavior should be the same as when we pass this attribute explicitly:

Product.new.settings #=>`{ "color" => "red"}`
Product.new(color: "red").settings #=>`{ "color" => "red"}`

Product.new.save!
#=> INSERT INTO products (settings) values ('{"color":"red"}'); 
Product.new(color: "red").save!
#=> INSERT INTO products (settings) values ('{"color":"red"}'); 

I think, we need a parity with Attributes API here:

# create_table :posts do |t|
#   t.string :data
# end
class Post < ActiveRecord::Base
  attribute :data, :datetime, default: -> { Time.current }
end

How does this behave? Not sure, need to check.

+1 that this would be valuable and should mirror the attributes API.

I'm gonna take a look at it this week if nobody minds.

Closed by #7 and released in 0.6.0