Skip to content

Instantly share code, notes, and snippets.

@danigb
Last active September 10, 2019 11:43
Show Gist options
  • Save danigb/117e3d90f39942434867dfc529b75445 to your computer and use it in GitHub Desktop.
Save danigb/117e3d90f39942434867dfc529b75445 to your computer and use it in GitHub Desktop.
Scoped variables localistico
# frozen_string_literal: true
##
# Variables resulting from the intersection two or more variables
# It's used by TemplateGallery to perform validation
class Variables::IntersectedVariables < Variables
def initialize(list)
@list = list
end
Variables.new.members.each do |name|
define_method name do
values = @list.map { |variables| variables.public_send(name) }
return nil if values.any?(nil)
return values.compact.first
end
end
end
# frozen_string_literal: true
RSpec.describe Variables::IntersectedVariables do
let(:one) { Variables.new(canonical_tag: '1') }
let(:two) { Variables.new(canonical_tag: '2', location: '2') }
let(:three) { Variables.new(canonical_tag: '3', location: '3', area: '3') }
let(:variables) { Variables::IntersectedVariables.new([one, two, three]) }
it 'uses hierarchy to find values' do
expect(variables.canonical_tag).to eq '1'
expect(variables.location).to be_nil
expect(variables.area).to be_nil
expect(variables.business).to be_nil
end
end
# frozen_string_literal: true
##
# Variables that uses a list of other variables to find values hierarchically
# (Not in use currently)
class Variables::ScopedVariables < Variables
def initialize(list)
@list = list
end
Variables.new.members.each do |name|
define_method name do
@list.each do |variables|
value = variables.public_send(name)
return value unless value.nil?
end
nil
end
end
end
# frozen_string_literal: true
RSpec.describe Variables::ScopedVariables do
let(:one) { Variables.new(canonical_tag: '1') }
let(:two) { Variables.new(canonical_tag: '2', location: '2') }
let(:three) { Variables.new(canonical_tag: '3', location: '3', area: '3') }
let(:variables) { Variables::ScopedVariables.new([one, two, three]) }
it 'uses hierarchy to find values' do
expect(variables.canonical_tag).to eq '1'
expect(variables.location).to eq '2'
expect(variables.area).to eq '3'
expect(variables.business).to be_nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment