add constant
This commit is contained in:
parent
ed2d9ed861
commit
58da4805fa
5 changed files with 93 additions and 0 deletions
17
app/models/logic.rb
Normal file
17
app/models/logic.rb
Normal file
|
@ -0,0 +1,17 @@
|
|||
module Logic
|
||||
def self.from_h(h)
|
||||
class_from_name(h['op']).from_h(h)
|
||||
end
|
||||
|
||||
def self.from_json(s)
|
||||
from_h(JSON.parse(s))
|
||||
end
|
||||
|
||||
def self.class_from_name(name)
|
||||
[Constant]
|
||||
.find { |c| c.name == name }
|
||||
end
|
||||
|
||||
def constant(value) = Logic::Constant.new(value)
|
||||
|
||||
end
|
39
app/models/logic/constant.rb
Normal file
39
app/models/logic/constant.rb
Normal file
|
@ -0,0 +1,39 @@
|
|||
class Logic::Constant < Logic::Term
|
||||
attr_reader :value
|
||||
|
||||
def initialize(value)
|
||||
@value = value
|
||||
end
|
||||
|
||||
def compute(_champs = nil) = @value
|
||||
|
||||
def to_s = @value.to_s
|
||||
|
||||
def type
|
||||
case @value
|
||||
when TrueClass, FalseClass
|
||||
:boolean
|
||||
when Integer, Float
|
||||
:number
|
||||
else
|
||||
@value.class.name.downcase.to_sym
|
||||
end
|
||||
end
|
||||
|
||||
def errors(_stable_ids = nil) = []
|
||||
|
||||
def to_h
|
||||
{
|
||||
"op" => self.class.name,
|
||||
"value" => @value
|
||||
}
|
||||
end
|
||||
|
||||
def self.from_h(h)
|
||||
self.new(h['value'])
|
||||
end
|
||||
|
||||
def ==(other)
|
||||
self.class == other.class && @value == other.value
|
||||
end
|
||||
end
|
5
app/models/logic/term.rb
Normal file
5
app/models/logic/term.rb
Normal file
|
@ -0,0 +1,5 @@
|
|||
class Logic::Term
|
||||
def to_json
|
||||
to_h.to_json
|
||||
end
|
||||
end
|
24
spec/models/logic/constant_spec.rb
Normal file
24
spec/models/logic/constant_spec.rb
Normal file
|
@ -0,0 +1,24 @@
|
|||
describe Logic::Constant do
|
||||
include Logic
|
||||
|
||||
describe '#compute' do
|
||||
it { expect(constant(1).compute).to eq(1) }
|
||||
end
|
||||
|
||||
describe '#type' do
|
||||
it { expect(constant(1).type).to eq(:number) }
|
||||
it { expect(constant(1.0).type).to eq(:number) }
|
||||
it { expect(constant('a').type).to eq(:string) }
|
||||
it { expect(constant(true).type).to eq(:boolean) }
|
||||
it { expect(constant(false).type).to eq(:boolean) }
|
||||
end
|
||||
|
||||
describe '#errors' do
|
||||
it { expect(constant(1).errors).to eq([]) }
|
||||
end
|
||||
|
||||
describe '#==' do
|
||||
it { expect(constant(1)).to eq(constant(1)) }
|
||||
it { expect(constant(1)).not_to eq(constant('a')) }
|
||||
end
|
||||
end
|
8
spec/models/logic_spec.rb
Normal file
8
spec/models/logic_spec.rb
Normal file
|
@ -0,0 +1,8 @@
|
|||
describe Logic do
|
||||
include Logic
|
||||
|
||||
it 'serializes deserializes' do
|
||||
expect(Logic.from_h(constant(1).to_h)).to eq(constant(1))
|
||||
expect(Logic.from_json(constant(1).to_json)).to eq(constant(1))
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue