module Merb class Request attr_accessor :env def initialize(env, method) @env = env @method = method end # returns true if the request is an ajax request. def xml_http_request? not /XMLHttpRequest/i.match(@env['HTTP_X_REQUESTED_WITH']).nil? end alias xhr? :xml_http_request? alias ajax? :xml_http_request? # returns the remote IP address if it can find it. def remote_ip return @env['HTTP_CLIENT_IP'] if @env.include?('HTTP_CLIENT_IP') if @env.include?(Mongrel::Const::HTTP_X_FORWARDED_FOR) then remote_ips = @env[Mongrel::Const::HTTP_X_FORWARDED_FOR].split(',').reject do |ip| ip =~ /^unknown$|^(127|10|172\.16|192\.168)\./i end return remote_ips.first.strip unless remote_ips.empty? end return @env[Mongrel::Const::REMOTE_ADDR] end # returns either 'https://' or 'http://' depending on # the HTTPS header def protocol ssl? ? 'https://' : 'http://' end # returns true if the request is an SSL request def ssl? @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https' end # returns the request HTTP_REFERER. def referer @env['HTTP_REFERER'] end # returns he request uri. def uri @env['REQUEST_URI'] end def user_agent @env['HTTP_USER_AGENT'] end def server_name @env['SERVER_NAME'] end def accept_encoding @env['HTTP_ACCEPT_ENCODING'] end def script_name @env['SCRIPT_NAME'] end def cache_control @env['HTTP_CACHE_CONTROL'] end def accept_language @env['HTTP_ACCEPT_LANGUAGE'] end def host @env['HTTP_HOST'] end def server_software @env['SERVER_SOFTWARE'] end def keep_alive @env['HTTP_KEEP_ALIVE'] end def accept_charset @env['HTTP_ACCEPT_CHARSET'] end def version @env['HTTP_VERSION'] end def gateway @env['GATEWAY_INTERFACE'] end def accept @env['HTTP_ACCEPT'] end def connection @env['HTTP_CONNECTION'] end def query_string @env['QUERY_STRING'] end # returns the uri without the query string. def path uri ? uri.split('?').first : '' end # returns the PATH_INFO def path_info @env['PATH_INFO'] end # returns the port the server is running on def port @env['SERVER_PORT'].to_i end # returns the full hostname including port def host @env['HTTP_X_FORWARDED_HOST'] || @env['HTTP_HOST'] end # returns an array of all the subdomain parts of the host. def subdomains(tld_length = 1) parts = host.split('.') parts[0..-(tld_length+2)] end # returns the full domain name without the port number. def domain(tld_length = 1) host.split('.').last(1 + tld_length).join('.').sub(/:\d+$/,'') end # returns the REQUEST_METHOD def method @method ||= @env['REQUEST_METHOD'].downcase.intern end # create predicate methods for querying the REQUEST_METHOD [:get, :post, :put, :delete, :head].each do |m| eval %{ def #{m}?; method == :#{m}; end } end end end