module ReportsHelper
def gradient_intercept(expression)
- expression.split(/x/).map(&:strip).map{|v| v.gsub(/\A[^0-9]+?|[^0-9]+?\z/, '') }
+ m = expression.scan(%r!\A(?:\(?(\-? *[0-9/ ]+?)\)? *\* *)?x(?: *(?:\+ *)?(-? *[0-9/ ]+?))?\z!).flatten
+ return %w[1 0] if m.all?(&:nil?)
+ m.map{|v| v ? v.gsub(/ */, "") : "1" }
end
end
require 'spec_helper'
describe ReportsHelper do
+ include ReportsHelper
- #Delete this example and add some real ones or delete this file
- it "should be included in the object returned by #helper" do
- included_modules = (class << helper; self; end).send :included_modules
- included_modules.should include(ReportsHelper)
+ describe "gradient_intercept" do
+ [
+ ["2 * x + 1" , ["2", "1"]],
+ ["-2 * x + 1" , ["-2", "1"]],
+ ["2 * x - 1" , ["2", "-1"]],
+ ["2*x+1" , ["2", "1"]],
+ ["-2*x+1" , ["-2", "1"]],
+ ["2*x-1" , ["2", "-1"]],
+ ["x" , ["1", "0"]],
+ ["x + 1" , ["1", "1"]],
+ ["x - 1" , ["1", "-1"]],
+ ["(1/2) * x + 1/2", ["1/2", "1/2"]],
+ ["(1 / 2) * x + 1 / 2", ["1/2", "1/2"]],
+ ["(-1 / 2) * x - 1 / 2", ["-1/2", "-1/2"]],
+ ].each do |expression, expected|
+ describe expression do
+ it{ gradient_intercept(expression).should == expected }
+ end
+ end
end
end