ruby 方便的片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 方便的片段相关的知识,希望对你有一定的参考价值。

class SomeRuleSet  
  def self.criteria
    constraints.map(&:description)
  end

  def self.constraints
    [
      Constraints::Max.new('something', 12, 'days', &:value),
      Constraints::Max.new('another', 42, 'months', &:value),
      Constraints::Match.new('example', nil, &:value),
      Constraints::Range.new('range example', 5, 10, &:value)
    ]
  end

  def self.run(some_object_array)
    some_object_array
      .map { |thing| Result.new(thing) }
      .each { |result| result.apply_constraints(constraints) }
  end
end

# result object
class Result
  attr_reader :thing

  def initialize(thing)
    @thing = thing
    @passed = true
    @fail_reasons = []
  end

  def apply_constraints(constraints)
    constraints.each do |constraint|
      result = constraint.evaluate(thing)
      @passed &&= result.passed
      @fail_reasons << result.detail unless result.passed
    end
  end

  def fail_reasons
    @fail_reasons.join(' ')
  end

  def passed?
    @passed
  end
end

# contraint result
module Constraints
  class Result
    attr_reader :passed, :skipped, :detail

    def initialize(passed, detail, skipped = false)
      @passed = passed
      @skipped = skipped
      @detail = detail
    end
  end
end

# example constraints
module Constraints
  class Max
    def initialize(item_name, amount, unit, &block)
      @amount = amount
      @item_name = item_name
      @block = block
      @unit = unit
    end

    def description
      "Max #{@item_name} of #{@amount} #{@unit}"
    end

    def evaluate(thing)
      val = @block.call(thing)
      if val.nil?
        Result.new(false, "There is no value for #{@item_name}.")
      elsif val <= @amount
        Result.new(true, "#{@item_name} is less than #{@amount} #{@unit}.")
      else
        Result.new(false, "max range reached for  #{@item_name}.")
      end
    end
  end
end

以上是关于ruby 方便的片段的主要内容,如果未能解决你的问题,请参考以下文章

ruby 我感兴趣的库中的代码片段

ruby 这个片段是一种简单的ruby方式,用于计算在Twitter上共享指定网址的次数。

ruby serverspec片段

ruby 片段

ruby Codiing片段

ruby RubySteps 012 - Rails - 迷你框架片段