我想在没有Sass引擎的类中使用Sass颜色函数.我已经在项目中使用了sass gem,所以我认为背负的东西很简单:
class Rectangle
include Sass::Script::Functions
def color
Sass::Script::Color.new([0x82, 0x39, 0x06])
end
def render
#haml engine executed with context of self
#so that within temlate i could call
# %stop{offset: '0%', stop: {color: lighten(color)}}
end
end
Run Code Online (Sandbox Code Playgroud)
更新:见#render上文,我想lighten(color)从一个Rectangle实例上下文中呈现的haml模板中调用
但我得到一个未定义的方法assert_type错误.该assert_type方法在Sass::Script::Functions::EvaluationContext类中定义.(github文件)
玩耍irb,只是为了得到一些接近我想要的东西看起来像这样:
require 'sass'
eval_context = Sass::Script::Functions::EvaluationContext.new({})
#yes the Sass::Script::Number.new(10) is requried, a simple 10 will not work
color = eval_context.rgb(Sass::Script::Number.new(10), Sass::Script::Number.new(10), Sass::Script::Number.new(10))
eval_context.lighten(color, Sass::Script::Number.new(10))
Run Code Online (Sandbox Code Playgroud)
这很疯狂 - 我错过了什么吗?
更新
既然我更好地理解了你的问题,为什么不重写功能呢?
require 'sass'
class Rectangle
include Sass::Script
def color
@color ||= Sass::Script::Color.new([0x82, 0x39, 0x06])
end
def lighten(ammount)
hsl = color.hsl.dup
hsl[2] += ammount
@color = Sass::Script::Color.new(hue: hsl[0], saturation: hsl[1], lightness: [2])
end
end
rec = Rectangle.new
rec.lighten(20)
Run Code Online (Sandbox Code Playgroud)
旧答案
你没有疯,你只是加入了错误的部分。
该代码按照您的预期运行。请注意,我::Functions从包含中删除了 。
require 'sass'
class Rectangle
include Sass::Script
def color
color = Sass::Script::Color.new([0x82, 0x39, 0x06])
puts color.class
end
end
rec = Rectangle.new
rec.color
Run Code Online (Sandbox Code Playgroud)