Sha256: efeb74079c92041ef5345ba7affa1ce01703476d543d0710b0ed21991c3f3026

Contents?: true

Size: 1.2 KB

Versions: 13

Compression:

Stored size: 1.2 KB

Contents

module AdminIt
  # Middleware request
  class Request < DelegateClass(Hash)
    ENV_KEY = 'admin_it.request'

    attr_reader :templates

    def initialize(env)
      @templates = {}
      @collections = {}
      @models = {}
      @env = env
      @process = false
      super({})
    end

    def process?
      @process == true
    end

    def process!
      @process = true
    end

    def self.get(request)
      return request if request.is_a?(self)
      fail 'Wrong request' unless request.is_a?(Rack::Request)
      request = request.env[ENV_KEY]
      fail 'rails_script middleware is not mounted' if request.nil?
      request
    end
  end

  # AdminIt middleware
  class Middleware
    SUBST_REGEXP = /<!--\s*(?<name>[a-zA-Z0-9_]+)\s*-->/

    def initialize(app)
      @app = app
    end

    def call(env)
      request = env[Request::ENV_KEY] = Request.new(env)
      status, headers, body = @app.call(env)
      if request.process?
        length = 0
        body.each do |str|
          str.gsub!(SUBST_REGEXP) { |s| request[SUBST_REGEXP.match(s)[1]] }
          length += str.bytesize
        end
        headers['Content-Length'] = length.to_s
      end
      [status, headers, body]
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
admin_it-1.3.8 lib/admin_it/middleware.rb
admin_it-1.3.7 lib/admin_it/middleware.rb
admin_it-1.3.6 lib/admin_it/middleware.rb
admin_it-1.3.5 lib/admin_it/middleware.rb
admin_it-1.3.4 lib/admin_it/middleware.rb
admin_it-1.3.3 lib/admin_it/middleware.rb
admin_it-1.3.2 lib/admin_it/middleware.rb
admin_it-1.3.1 lib/admin_it/middleware.rb
admin_it-1.3.0 lib/admin_it/middleware.rb
admin_it-1.2.8 lib/admin_it/middleware.rb
admin_it-1.2.7 lib/admin_it/middleware.rb
admin_it-1.2.6 lib/admin_it/middleware.rb
admin_it-1.2.5 lib/admin_it/middleware.rb