Is it possible to call super to invoke alias method in a method that is being aliased - ruby-on-rails

Let's say in the activerecord model car there are two boolean fields: suv and blue
If there is a method in the car model defined as such
def suv
something_true? ? super : false
end
alias :blue :suv
Now if something_true? is true, the "super" works if i invoke car.suv. However, it does not work if i invoke car.blue, then the car.blue instead returns the value of suv stored in the database. Is there anyway to make this work?

It's a clever idea but I don't think it will work. Even if it's accessed through an alias, calling super inside the method suv will only call suv. You can use metaprogramming though:
class A
def a; 1; end
def b; 2; end
end
class B < A
def initialize(condition)
#condition = condition
end
%i{a b}.each do |fn|
define_method(fn) do
#condition ? super() : "default"
end
end
end
puts B.new(false).a # => "default"
puts B.new(false).b # => "default"
puts B.new(true).a # => 1
puts B.new(true).b # => 2

Related

Neat way to get and set keys of json column in Rails

I have a model/table with a json column in it as follows
t.json :options, default: {}
The column can contain many keys within it, something like this
options = {"details" : {key1: "Value1", key2: "Value2"}}
I want to set and get these values easily. So i have made getters and setters for the same.
def key1
options['details']&.[]('key1')
end
def key1=(value)
options['details'] ||= {}
options['details']['key1'] ||=0
options['details']['key1'] += value
end
But this just adds lines to my code, and it does not scale when more details are added. Can you please suggest a clean and neat way of doing this?
Use dynamic method creation:
options['details'].default_proc = ->(_,_) {{}}
ALLOWED_KEYS = %i[key1 key2 key3]
ALLOWED_KEYS.each do |key|
define_method key do
options['details'][key] if options['details'].key?(key)
end
define_method "#{key}=" do |value|
(options['details'][key] ||= 0) += value
end
end
You can just pass the key as a parameter as well right?
def get_key key=:key1
options['details']&.[](key)
end
def set_key= value, key=:key1
options['details'] ||= {}
options['details'][key] ||=0
options['details'][key] += value
end
Simple & Short
Depending on re-usability you can choose different options. The short option is to simply define the methods using a loop in combination with #define_method.
class SomeModel < ApplicationRecord
option_accessors = ['key1', 'key2']
option_accessors.map(&:to_s).each do |accessor_name|
# ^ in case you provide symbols in option_accessors
# this can be left out if know this is not the case
define_method accessor_name do
options.dig('details', accessor_name)
end
define_method "#{accessor_name}=" do |value|
details = options['details'] ||= {}
details[accessor_name] ||= 0
details[accessor_name] += value
end
end
end
Writing a Module
Alternatively you could write a module that provide the above as helpers. A simple module could look something like this:
# app/model_helpers/option_details_attribute_accessors.rb
module OptionDetailsAttributeAccessors
def option_details_attr_reader(*accessors)
accessors.map(&:to_s).each do |accessor|
define_method accessor do
options.dig('details', accessor)
end
end
end
def option_details_attr_writer(*accessors)
accessors.map(&:to_s).each do |accessor|
define_method "#{accessor}=" do |value|
details = options['details'] ||= {}
details[accessor] ||= 0
details[accessor] += value
end
end
end
def option_details_attr_accessor(*accessors)
option_details_attr_reader(*accessors)
option_details_attr_writer(*accessors)
end
end
Now you can simply extend your class with these helpers and easily add readers/writers.
class SomeModel < ApplicationRecord
extend OptionDetailsAttributeAccessors
option_details_attr_accessor :key1, :key2
end
If anything is unclear simply ask away in the comments.

Minitest::Mock#expect without specific order?

Suppose I have a class:
class Foo
def process
MyModel.where(id: [1,3,5,7]).each do |my_model|
ExternalService.dispatch(my_modal.id)
end
end
end
I want to test it:
class FooTest < ActiveSupport::TestCase
def process_test
external_service_mock = MiniTest::Mock.new
[1,3,5,7].each do |id|
external_service_mock.expect(:call, true, id)
end
ExternalService.stub(:dispatch, events_mock) do
Foo.new.process
end
external_service_mock.verify
end
end
However, #expect enforces that the following calls are made in the same order as #expect was called. That's not good for me, because I have no confidence, in what order will the results be returned by the DB.
How can I solve this problem? Is there a way to expect calls without specific order?
Try Using a Set
require 'set'
xs = Set[3,5,7,9]
#cat = Minitest::Mock.new
#cat.expect :meow?, true, [xs]
#cat.meow? 7 # => ok...
#cat.expect :meow?, true, [xs]
#cat.meow? 4 # => boom!
Alternatively, a less specific option:
Given that the value returned by the mock isn't a function of the parameter value, perhaps you can just specify a class for the parameter when setting up your mock. Here's an example of a cat that expects meow? to be called four times with an arbitrary integer.
#cat = Minitest::Mock.new
4.times { #cat.expect(:meow?, true, [Integer]) }
# Yep, I can meow thrice.
#cat.meow? 3 # => true
# Mope, I can't meow a potato number of times.
#cat.meow? "potato" # => MockExpectationError

How can I cleanly define "antonym" or "opposite" methods in Ruby / Rails?

I'm pretty often defining methods and their antonyms in the code I'm writing, as in:
def happy?
#happiness > 3
end
def sad?
!happy?
end
Which is fine, but I'm a little surprised that Ruby or ActiveSupport doesn't give me something like:
def happy?
#happiness > 3
end
alias_opposite :sad? :happy?
Or am I just looking in the wrong place?
There is no such method in popular libraries, but there is how this could be implemented
class Module
def alias_opposite(a, b)
define_method(a) { !self.send(b) }
end
end
Usage
class A < Struct.new(:happiness)
def happy?
happiness > 3
end
alias_opposite :sad?, :happy?
end
p A.new(1).sad? # => true
p A.new(5).sad? # => false
I suspect this pattern is not as common in ruby because the unless keyword often does the trick:
# ...
clap_your_hands if happy?
stomp_your_feet unless happy?
# ...
Of course, its simple to roll your own:
module Antonymator
def define_antonym(as, of)
define_method(as.to_sym) do |*args|
return !(send(of.to_sym, *args))
end
end
end
# Usage Example
class AreThey
extend Antonymator
define_antonym :uneql?, :eql?
define_antonym :nonconsecutive?, :consecutive?
def eql?(a, b)
a == b
end
def consecutive?(a, b)
a.next == b
end
end
are_they = AreThey.new
puts are_they.uneql? 1, 2 # true
puts are_they.nonconsecutive? 1, 2 # false
If your methods return a Boolean, you can always include the positive method in the negative method.
def drinking_age?(age)
age > #restricted_age
end
def not_drinking_age?(age)
!drinking_age?(age)
end
#restricted_age = 20
Hope that helps.
I guess it depends on what 'opposite' means in the context.

Array of objects in ruby

I am trying to learn ruby and have a doubt regarding passing arrays of objects as function parameters and printing it in the function.
I have an array that contains an array of objects as follows
describe Name
par1 = "John"
par2 = "Miley"
par3 = "Maria"
#obj_arr = [Name.new(par1),Name.new(par2),Name.new(par3)]
Name.func1(#obj_arr)
I want to print the name "John", "Miley" and "Maria" in the function and I wrote the function func1 is as follows :
def self.func1(parameter)
parameter.each do |p|
puts p
end
end
This did not print the names. Am I going wrong in accessing the obj_arr in the function?
I think your problem might be the to_s method of the object. You should override it to print what you want. BTW, the syntax in your question is a bit off. I think the definition of the function should be def self.func1 and that your missing an end.
This is the code I tested:
irb(main):001:0> class Name
irb(main):002:1> def self.func1(parameter)
irb(main):003:2> parameter.each do |p|
irb(main):004:3* puts p
irb(main):005:3> end
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> class Name
irb(main):009:1> def initialize(name)
irb(main):010:2> #name = name
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> Name.func1([Name.new('a'), Name.new('b')])
#<Name:0x2163dc8>
#<Name:0x2163d98>
=> [#<Name:0x2163dc8 #name="a">, #<Name:0x2163d98 #name="b">]
irb(main):014:0> class Name
irb(main):015:1> def to_s
irb(main):016:2> #name
irb(main):017:2> end
irb(main):018:1> end
=> nil
irb(main):019:0> Name.func1([Name.new('a'), Name.new('b')])
a
b
=> [a, b]
irb(main):020:0>
It may be that func1 is defined on a instance of class Name and not the class itself?
Try:
class Name
def self.func1(parameter)
parameter.each do |p|
puts p
end
end
end

How do I pass a var from one model's method to another?

Here is my one model..
CardSignup.rb
def credit_status_on_create
Organization.find(self.organization_id).update_credits
end
And here's my other model. As you can see what I wrote here is an incorrect way to pass the var
def update_credits
#organization = Organization.find(params[:id])
credit_count = #organization.card_signups.select { |c| c.credit_status == true}.count
end
If it can't be done by (params[:id]), what can it be done by?
Thanks!
Ideally the data accessible to the controller should be passed as parameter to model methods. So I advise you to see if it is possible to rewrite your code. But here are two possible solutions to your problem. I prefer the later approach as it is generic.
Approach 1: Declare a virtual attribute
class CardSignup
attr_accessor call_context
def call_context
#call_context || {}
end
end
In your controller code:
def create
cs = CardSignup.new(...)
cs.call_context = params
if cs.save
# success
else
# error
end
end
In your CardSignup model:
def credit_status_on_create
Organization.find(self.organization_id).update_credits(call_context)
end
Update the Organization model. Note the change to your count logic.
def update_credits
#organization = Organization.find(call_context[:id])
credit_count = #organization.card_signups.count(:conditions =>
{:credit_status => true})
end
Approach 2: Declare a thread local variable accessible to all models
Your controller code:
def create
Thread.local[:call_context] = params
cs = CardSignup.new(...)
if cs.save
# success
else
# error
end
end
Update the Organization model. Note the change to your count logic.
def update_credits
#organization = Organization.find((Thread.local[:call_context] ||{})[:id])
credit_count = #organization.card_signups.count(:conditions =>
{:credit_status => true})
end
Use an attr_accessor.
E.g.,
class << self
#myvar = "something for all instances of model"
attr_accessor :myvar
end
#myothervar = "something for initialized instances"
attr_accessor :myothervar
then you can access them as ModelName.myvar and ModelName.new.myvar respectively.
You don't say whether you're using Rails 2 or 3 but let's assume Rails 2 for this purpose (Rails 3 provides the a new DSL for constructing queries).
You could consider creating a named scope for in your Organization model as follows:
named_scope :update_credits,
lambda { |id| { :include => :card_signup, :conditions => [ "id = ? AND card_signups.credit_status = TRUE", id ] } }
And then use it as follows:
def credit_status_on_create
Organization.update_credits(self.organization_id)
end
Admittedly I don't quite understand the role of the counter in your logic but I'm sure you could craft that back into this suggestion if you adopt it.

Resources