RubyのCookie読み込みで躓いています

このQ&Aのポイント
  • RubyのCookie読み込みで問題が発生しています。
  • Cookieからの情報を正しく取得する方法を教えてください。
  • 特定の文字列を取り除いて値のみを取得したいです。
回答を見る
  • ベストアンサー

RubyのCookie読み込みにで躓いており、質問させて頂きました。

RubyのCookie読み込みにで躓いており、質問させて頂きました。 ------------------------------------------------------------------------------------ module Main def Cookie_r(cookie_kye = "") require "cgi" cgi = CGI.new cgi.cookies[cookie_kye]#.gsub(cookie_kye, "").gsub("; path=/cgi-bin/","") end end include Main print Cookie_r("userid") ------------------------------------------------------------------------------------ 結果:userid=1; path=/cgi-bin/ 「; path=/cgi-bin/」 は削除して「1」と返して欲しいのですが、 #以下の.gsubを記入すると応答してくれません。 「1」と回答させるにはどのようにすれば良いか?教えて頂けないでしょうか? 環境: ・windows_xp_sp3+iis ・ActiveScriptRuby 1.8.7 ・IE8

  • Ruby
  • 回答数2
  • ありがとう数5

質問者が選んだベストアンサー

  • ベストアンサー
  • notnot
  • ベストアンサー率47% (4845/10255)
回答No.2

ツッコミ所が多いのですが、 useridというCookieの値が1であれば、cgi.cookies["userid"] は、["1"] を返しますので、 require "cgi" cgi = CGI.new print cgi.cookies["userid"][0]

go_to_orz
質問者

お礼

有難うございました。無事クッキの取得ができました。

その他の回答 (1)

回答No.1

#はコメントですので、取り除けばうまく動くのではないかと思います。

go_to_orz
質問者

補足

すみません、質問事項に漏れておりました。 #を取ると真っ白なページが表示されてしまいます。 print Cookie_r("userid")].gsub(cookie_kye, "").gsub("; path=/cgi-bin/","") とした場合も同じく白紙になってしまいます。 ご存知でしたら教えていただけると助かります。

関連するQ&A

  • Cookieの期限設定の書式について

    現在ASPでCookieを使用しております。以下のように、 Response.Cookies("UserID")=UserID Response.Cookies("UserID").Domain="aaaa.co.jp" Response.Cookies("UserID").Expires= DateAdd("n",5, Now) Response.Cookies("UserID").Path="/" Response.Cookies("ItemID")=ItemID Response.Cookies("ItemID").Domain="aaaa.co.jp" Response.Cookies("ItemID").Expires= DateAdd("n",5, Now) Response.Cookies("ItemID").Path="/" の様に期限の設定をしているのですが、上手く期限が設定できていないのか、 期限時刻を過ぎてもCookieが残ってしまいます。 Cookieの期限の書式は、 [書式]Sun, 21-Feb-2002 02:22:54 GMT と決められている様ですが、上記のASPの場合 2005/07/10 22:15:42 という値が入っているから期限が上手く設定できていないのでしょうか? 分刻みで時間を足したいのですが、上記のCookieの書式のように、曜日から きちんと同じ書式で無いと期限は上手く設定されないのでしょうか?

  • Cookieが正しく取得できない

    domain="xxxx.com" path="/" でセットしたCookieを <script type="text/javascript" src="aaa.xxxx.com/cgi-bin/aaaa.cgi"></script> と指定したCGIで取得できない。 通常であれば domain="xxxx.com" path="/" でセットしたCookieを http://aaa.xxxx.com/cgi-bin/aaaa.cgi にアクセスした際に取得することはできるはずですが、 <script src="・・・・・・"></script> の形で指定すると取得できなくなることはあるのでしょうか?

  • ruby erbでの表示がうまく行きません。

    本当に初心者ですので、質問が分かりづらいかもしれませんが、よろしくお願いします。 環境は、OS:WindowsXPSP3 ApacheHttpserver2.2 Ruby-186-26 RubyGems -v 0.9.4 です。 erbを使って簡易掲示版を作ろう!!と言うものなのですが、 ・keijiban.html ・keijiban.rb ・data.csv(書き込んだデータ保存用csv)・・・cgi-binに保存 ************************************************************ 入力ミスは散々見直しました。 添付ファイルが2つのファイルです。localhostで表示してみていますが、 初期表示は出来ますが、データを追加しようと『投稿する』ボタンをクリックすると 画面が真っ白になります。 入力ミスは散々見直しました。 初期表示が出来ると言う事は、keijiban.rbは動作していると思われます。 REDで簡易解析と言うのをしてみた所、次のエラーが出たり出なかったりです。 C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require': no such file to load -- rde (LoadError) from C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' from C:\Program Files\RDE\rde_export.rb:9 from C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require' from C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require' from C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/rb1D.tmp:71 Complete(1) 何か、インストールが足りないのでしょうか? 教えて下さい。 2000字超えたため、別ファイルに全文を記入しています。

    • ベストアンサー
    • Ruby
  • Ruby net/httpについて

    Rubyで#!/ruby/bin/ruby require 'net/http' require 'uri' print "content-type: text/html\r\n\r\n"; begin url = "http://~~~.com/" Net::HTTP.get_print URI.parse(url) rescue => ex print ex.class; print "<hr />"; print ex.message; print "<hr />"; print ex.backtrace; end というようなコードで指定のURLの内容をgetしたいと思っています。 が、とりあえずは上記内容でURL先の内容は取得できるのですが url = "http://www.~~~.com"; という風にwwwをつけるとスクリプトがうごかずURL先の内容が取得できないのです。 原因はなんなのでしょうか? 識者のかたご教授ください。

    • ベストアンサー
    • Ruby
  • Ruby/DBIが上手く動きません。。

    http://code.nanigac.com/source/wiki/view/496 上記のサイトさんを参考にRubyからMySQLのデータベースにアクセスするプログラムを作りました。 コマンドプロンプト上では動作するのですが、同パソコンでブラウザから開くとエラーをはきます。 どなたか理由を教えていただけないでしょうか? 環境 WindowsXP Professional Apache 2.0.63 ruby 1.8.6 dbi-0.2.0 MySQL 5.0.51a [ソースコード] #!/user/local/bin/ruby print "Content-type: text/html\n\n" def error_cgi() print "*** CGI Error List ***<br />" print "#{CGI.escapeHTML($!.inspect)}<br />" $@.each {|x| print CGI.escapeHTML(x), "<br />"} end begin require "dbi" require "cgi" print <<EOF <html> <head> <title>データベース</title> </head> <body> EOF # MySQLサーバへ接続 dbh = DBI.connect("dbi:Mysql:test:localhost", "testuser", "testpass") # サーババージョンの文字列を取得して、表示する。 row = dbh.select_one("SELECT VERSION()") print "Server version: #{row[0]}\n" print <<EOF </body> </html> EOF rescue DBI::DatabaseError => e print "An error occurred" print "Error code: #{e.err}" print "Error message: #{e.errstr}" rescue error_cgi() ensure # サーバから切断 dbh.disconnect if dbh end [プロンプト] Content-type: text/html <html> <head> <title>データベース</title> </head> <body> Server version: 5.0.51a-community-nt </body> </html> [ブラウザでのエラー] *** CGI Error List *** #<DBI::InterfaceError: Could not load driver (no such file to load -- C:/user/local/lib/ruby/site_ruby/1.8/dbd/Mysql)> C:/user/local/lib/ruby/site_ruby/1.8/dbi.rb:368:in `load_driver' C:/user/local/lib/ruby/site_ruby/1.8/dbi.rb:233:in `_get_full_driver' C:/user/local/lib/ruby/site_ruby/1.8/dbi.rb:219:in `connect' D:/Development/NotePC WEB/public_html/cgi-bin/database.rb:24

  • Ruby WEBrick cgiからgifが最後まで送れない。

    以下のようなHTTPサーバをWinXp上で動かしました。 #$ruby = "C:/ruby/bin/ruby.exe" require 'webrick' srv = WEBrick::HTTPServer.new({ :BindAddress => 'xxx.xxx.xxx.xxx', :CGIInterpreter => "c:/ruby/bin/ruby.exe", :Port => 80 }) srv.mount("/", WEBrick::HTTPServlet::FileHandler, "./", {:FancyIndexing=>true}) srv.start そして、以下のようなCGIをよびます。 #!/usr/bin/ruby STDOUT.binmode open("hoge.gif", "r") do |f| f.binmode body = f.read puts "content-type: image/gif" puts "content-length: #{body.size.to_s}" puts "" print body end すると、content-length分のHTTPボディーが送られてきません。 2種類のgifで試しましたが、193byte/724byte、289byte/451byteでした。 バージョンは、ruby 1.8.6、WEBrick 1.3.1です。 何が原因でしょうか?

  • Ruby 演算子 "==="

    Rubyの演算子 "===" についての質問です。 例:Rubyリファレンスより抜粋 require 'uri' require 'net/http' Net::HTTP.version_1_2 # おまじない def fetch( uri_str, limit = 10 ) # 適切な例外クラスに変えるべき raise ArgumentError, 'http redirect too deep' if limit == 0 response = Net::HTTP.get_response(URI.parse(uri_str)) case response when Net::HTTPSuccess then response when Net::HTTPRedirection then fetch(response['location'], limit - 1) else response.error! end end HTTPRedirectionが起きたと仮定して。 この case文だと思った通りの動きをします。 しかし、case文の部分を if response == Net::HTTPRedirection としたところ if文の中に入ってきません。何故でしょう? if response === Net::HTTPRedirection としても同じ結果でした。 Rubyを勉強しはじめて 初日からこんな調子ですが 宜しくお願いいたします。

  • ruby-cgi メールは受信できるのですが文字化けしてしまいます。

    下記のように記載しましたが、日本語のメール本文が文字化けしてしまいます。 nkfあたりが怪しいと思うのですが、お手上げです。 よろしくお願いします。 #!/usr/bin/ruby -Ke require 'nkf' require 'cgi' require 'net/smtp' def sendmail(server, subject, body, sender, recipient) mail = '' # メールヘッダを作る mail << 'To: ' + recipient + "\n" mail << 'From: ' + sender + "\n" mail << 'Subject: ' + subject + "\n" mail << 'Date: ' + Time.now.strftime('%a, %d %b %Y %H:%M:%S %z') + "\n" mail << "\n" # メールの本文 mail << body # 送信! Net::SMTP.start(server, 25) {|smtp| smtp.send_mail(mail, sender, recipient) } end cgi = CGI.new output = '' output << "ああ" + ":\n" output << ' ' + "いいい".gsub(/\n/, "\n ") + "\n" NKF.nkf('-j -m0', output) sendmail('mailserver@**.co.jp', 'cgi sendmail', output, 'from@mail.co.jp', 'to@mail.co.jp'){|body| NKF.nkf('-e -m0', body) } cgi.out('type' => 'text/plain') { output }

    • ベストアンサー
    • CGI
  • 【ruby】クラスCGIを改造して、クエリの文字コードを変えたい

    クエリパラメータを取得するのにCGIクラスを使っています。 Rubyのマニュアルでは『フォームフィールドの値を得る』として以下の様に記載してあります。 require "cgi" cgi = CGI.new values = cgi['field_name'] # <== 'field_name' の配列 私が使用しているサーバはWindowsサーバでして、取得したクエリ(フォームフィールド)は文字コードをs-jisに変換して使う事が大半です。 そこで、CGIクラスそのものを改造して、いちいちvalues.tosjisしなくてもよい様にしたいです。 実は以前に、同じような事を質問してまして(http://oshiete1.goo.ne.jp/qa4944090.html)alias を使えばこのようなことが出来るかなと思い、以下の様に書いてみました。(行頭は全角スペースです。) #!/usr/local/bin/ruby require 'cgi' require 'kconv' STDOUT.binmode STDIN.binmode class CGI  alias :initialize_orig :initialize  def initialize()   hash=initialize_orig()   hash.each do|key,val|    hash[key]=val.collect{|x|x.tosjis}   end   hash  end end cgi=CGI.new if cgi.has_key?('arg') then  STDERR.puts cgi['arg']  cgi.out(){'ok'} end 結果は `initialize': undefined method `each' for nil: NilClass (NoMethodError) で実行不可でした。 initializeはリターンできないからかな。 次に、 class CGI  alias :params_orig :params  def params()   hash=params_orig   hash.each do|key,val|    hash[key]=val.collect{|x|'*' + x + '*'}   end  hash end end などとも書いてみましたが、 undefined method `params' for class `CGI' で実行不可でした。 ご指導のほど、よろしくお願いいたします。

    • ベストアンサー
    • Ruby
  • Ruby:CGI Content-Type: の設定方法

    以下に示すcgiの実行結果をContent-Type: application/x-javascriptにしたいのですが、どうしたら良いですか? #!/usr/local/bin/ruby require "cgi" cgi = CGI.new time=Time.new cgi.out do "document.write(\"#{time}\");" end

専門家に質問してみよう