DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.04k stars 85 forks source link

Override methods #144

Open vojta0001 opened 1 year ago

vojta0001 commented 1 year ago

Hello,

I would like to override access methods in some store model class for example Post with attribute content of type string where I would like to add translation of data, similar as mobility gem. Raw data for the content attribute looks as {"en": "locale en", "cs": "locale cs"} and reader returns only locale which is already set. In writer update value for specific locale or update directly by method method_#{locale}.

I have already tried it, but without any success where I had problem to get the old value for this attribute in writer method. So is possible to get old and new values in writer to make some changes with both values?

DmitryTsepelev commented 1 year ago

Hey!

Could you provide the runnable code snippet for the thing you want to get?

vojta0001 commented 1 year ago

yes, here is some code snippet:

I would like do this: description has saved this value: "{\"en\":\"locale en\", \"cs\":\"locale cs\"}" and locale is hardcoded to: "en"

Is possible do it directly in rewritten methods for description attribute?

DmitryTsepelev commented 1 year ago

@vojta0001 looks like method gets overriden somewhere, but this seems to work

class JsonModel::Lesson < JsonModel::Base
  LOCALE = 'en'

  attribute :duration, :float
  attribute :description

  def initialize(attributes = nil)
    super(attributes)
  end

  def description_localized
    description[LOCALE]
  end

  def description_localized=(val)
    description[LOCALE] = val
  end
end