Skip to content

Separate getter, setter and attribute value #36

@schmijos

Description

@schmijos

I tried something like this:

CleanShot.2024-11-15.at.12.40.27.mp4
class Row < ApplicationRecord
  [*"A".."Z"].each do |letter|
    define_method(letter) do
      evaluate(self[letter])
    end

    define_method("#{letter}=") do |value|
      self[letter] = value
    end
  end

  def evaluate(value)
    return value unless value.is_a?(String) && value.start_with?('=')

    begin
      formula = value[1..] # Strip the '=' prefix
      formula.gsub!(/\$([A-Z])\$([0-9]+)/) do |match|
        col = Regexp.last_match(1)
        row = Regexp.last_match(2).to_i
        referenced_row = self.class.find(row)
        referenced_row.send(col)
      end

      eval(formula)
    rescue StandardError => e
      "Error: #{e.message}"
    end
  end
end

This use case would need a separation of attribute=, attribute and self[:attribute].
I'd like to see the getter value, but I'd like to edit the value in the database.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions