Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override methods #144

Open
vojta0001 opened this issue Mar 12, 2023 · 3 comments
Open

Override methods #144

vojta0001 opened this issue Mar 12, 2023 · 3 comments

Comments

@vojta0001
Copy link

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
Copy link
Owner

Hey!

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

@vojta0001
Copy link
Author

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"

  • so when I will read it then in my rewritten description method will return only data for specific locale, so in this case: "locale en"

  • and if I will want to update this value, for example with new value: "locale en updated" then my rewritten method for description load actual data for description, update it for locale "en" and new value then will be this: "{\"en\":\"locale en updated\", \"cs\":\"locale cs\"}"

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

@DmitryTsepelev
Copy link
Owner

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants