Class: Rack::Rewrite

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_rewrite.rb,
lib/rack_rewrite/actions.rb,
lib/rack_rewrite/condition_set.rb

Defined Under Namespace

Classes: Action, ConditionSet

Constant Summary collapse

FailError =
Class.new(RuntimeError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}, &block) ⇒ Rewrite

Returns a new instance of Rewrite.



13
14
15
16
17
18
# File 'lib/rack_rewrite.rb', line 13

def initialize(app, options = {}, &block)
  @app = app
  @options = []
  @current_condition_set = @root = ConditionSet.new(nil)
  instance_eval(&block)
end

Instance Attribute Details

#headersObject

Returns the value of attribute headers.



11
12
13
# File 'lib/rack_rewrite.rb', line 11

def headers
  @headers
end

#pathObject

Returns the value of attribute path.



11
12
13
# File 'lib/rack_rewrite.rb', line 11

def path
  @path
end

#redirect(*args, &block) ⇒ Object

Returns the value of attribute redirect.



11
12
13
# File 'lib/rack_rewrite.rb', line 11

def redirect
  @redirect
end

Instance Method Details

#act(&block) ⇒ Object



31
32
33
# File 'lib/rack_rewrite.rb', line 31

def act(&block)
  @current_condition_set.actions << Action::Do.new(self, block)
end

#call(env) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rack_rewrite.rb', line 49

def call(env)
  @headers = {}
  catch(:pass) {
    env = call_conditions(env, @root)
    raise FailError.new
  }
  if @redirect
    redirect = @redirect
    @redirect = nil
    redirect
  else
    (status, headers, body) = @app.call(env)
    [status, headers.merge(@headers), body]
  end
end

#call_conditions(env, conditions_set) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rack_rewrite.rb', line 65

def call_conditions(env, conditions_set)
  if conditions_set.satisfied?(env)
    conditions_set.actions.each_with_index do |act, index|
      break if @done
      case act
      when ConditionSet
        call_conditions(env, act)
      else
        env = act.call(env)
      end
    end
  end
  
end

#failObject



39
40
41
# File 'lib/rack_rewrite.rb', line 39

def fail
  @current_condition_set.actions << Action::Fail.new
end

#on(conditions = {}, &block) ⇒ Object



20
21
22
23
24
25
# File 'lib/rack_rewrite.rb', line 20

def on(conditions = {}, &block)
  @current_condition_set.actions << ConditionSet.new(@current_condition_set, conditions)
  @current_condition_set = @current_condition_set.actions.last
  instance_eval(&block)
  @current_condition_set = @current_condition_set.parent_set
end

#passObject



35
36
37
# File 'lib/rack_rewrite.rb', line 35

def pass
  @current_condition_set.actions << Action::Pass.new
end

#set(variable, pattern = nil, &block) ⇒ Object



27
28
29
# File 'lib/rack_rewrite.rb', line 27

def set(variable, pattern = nil, &block)
  @current_condition_set.actions << Action::Set.new(variable, pattern || block)
end