小编Sid*_*Sid的帖子

Ruby通过引用或值传递吗?

@user.update_languages(params[:language][:language1], 
                       params[:language][:language2], 
                       params[:language][:language3])
lang_errors = @user.errors
logger.debug "--------------------LANG_ERRORS----------101-------------" 
                + lang_errors.full_messages.inspect

if params[:user]
  @user.state = params[:user][:state]
  success = success & @user.save
end
logger.debug "--------------------LANG_ERRORS-------------102----------" 
                + lang_errors.full_messages.inspect

if lang_errors.full_messages.empty?
Run Code Online (Sandbox Code Playgroud)

@userobject会向方法中的lang_errors变量添加错误update_lanugages.当我对@user对象执行保存时,我丢失了最初存储在lang_errors变量中的错误.

虽然我试图做的更多是一个黑客(似乎没有工作).我想了解为什么变量值被淘汰了.我理解通过引用传递,所以我想知道如何在不被淘汰的情况下将该值保存在该变量中.

ruby ruby-on-rails pass-by-reference

245
推荐指数
8
解决办法
10万
查看次数

如何在没有开始和结束块的情况下在Ruby中使用rescue

我知道有一个开始救援结束的标准技术

如何单独使用救援区.

它是如何工作的以及它如何知道正在监视哪些代码?

ruby

111
推荐指数
5
解决办法
3万
查看次数

正在呈现的Rspec测试模板

我试图测试成功注册的条件,成功模板由以下控制器代码呈现


def create
    @user = User.new(params[:user])
    if @user.save
      render :template => "success"
    else
      flash[:notice] = "Oops Somethings not quite right! :("
      render :action => "new"
    end
  end

我使用以下规范来测试此代码


 before(:each) do
    @user = User.new
    @user.attributes = valid_attributes    
    @params = valid_attributes
    @user.stub!(:save).and_return(true)
  end


  def do_post
    post :create
  end


  it "should create new user " do
    count = User.count
    do_post
    user = User.new(@params)    
    user.save.should eql(true)
    User.count.should eql(count + 1)

  end

  it "should render the success page on successful signup" do
    do_post
    @user.save
    response.should …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails

17
推荐指数
1
解决办法
2万
查看次数

Ruby readpartial和read_nonblock没有抛出EOFError

我正在尝试理解并重新创建一个简单的preforking服务器,沿着独角兽的线路,服务器启动分叉4进程,所有进程都在控制套接字上等待(接受).

控制套接字@control_socket绑定到9799并生成4个等待接受连接的worker.对每个工人所做的工作如下


        def spawn_child
            fork do
                $STDOUT.puts "Forking child #{Process.pid}"
                loop do 
                    @client = @control_socket.accept                                        
                    loop do                     
                        request = gets              

                        if request                          
                            respond(@inner_app.call(request))                           
                        else
                            $STDOUT.puts("No Request")
                            @client.close                           
                        end
                    end
                end
            end
        end

我使用了一个非常简单的机架应用程序,它只返回一个状态代码为200的字符串和一个text-type of text/html.

我面临的问题是我的服务器工作正常,当我读取传入的请求(通过在" http:// localhost:9799 " 点击网址)使用gets而不是像readread_partialread_nonblock.当我使用非阻塞读取时,似乎永远不会抛出EOFError,根据我的理解,它意味着它不会接收EOF状态.

这会导致读取loop无法完成.这是完成这项工作的代码片段.


        # Reads a file using IO.read_nonblock
        # Returns end of file when using get but doesn't seem to return 
        # while using read_nonblock or readpartial …
Run Code Online (Sandbox Code Playgroud)

ruby unix nonblocking preforking unicorn

12
推荐指数
1
解决办法
3051
查看次数

FullCalendar事件仅在Safari上显示

我一直在使用FullCalendar插件,我已经设法让它在FF和Chrome中运行,但我似乎无法理解为什么这些事件不会出现在Safari上.

我使用Rails后端将事件作为数组获取.这是FireBug显示的事件的JSON对象.

_end: Invalid Date    
_id: "1953"   
_start: Fri Feb 10 2012 00:00:00 GMT+0530 (IST)  
allDay: false  
backgroundColor: "#F60 !important"  
className: Array[0]  
color: "#FFFFFF !important"  
description: ""  
end: Invalid Date  
start: Fri Feb 10 2012 00:00:00 GMT+0530 (IST)   
textColor: "#FFFFFF !important"   
__proto__: Object   
Run Code Online (Sandbox Code Playgroud)

我在safari控制台上没有错误.无效的结束日期显示null在FF和Chrome上.

以下是我填充事件的方式

event[:id]                        = each_event.id    
event[:title]                = each_event.event_title    
event[:allDay]               = each_event.all_day?   
event[:start]                = each_event.start_time.strftime('%Y-%m-%d %H:%M:00')    
event[:end] = each_event.end_date.to_time.strftime('%Y-%m-%d %H:%M:00') if each_event.end_date.present?          
event[:color]                = '#FFFFFF !important'      
event[:backgroundColor]      = (each_event.user ==  current_user) ? '#F60 !important' : '#090 …
Run Code Online (Sandbox Code Playgroud)

safari jquery ruby-on-rails fullcalendar

11
推荐指数
1
解决办法
4327
查看次数

net/http.rb:560:在`initialize'中:getaddrinfo:名称或服务未知(SocketError)

@@timestamp = nil

def generate_oauth_url
  @@timestamp = timestamp
  url = CONNECT_URL + REQUEST_TOKEN_PATH + "&oauth_callback=#{OAUTH_CALLBACK}&oauth_consumer_key=#{OAUTH_CONSUMER_KEY}&oauth_nonce=#{NONCE}    &oauth_signature_method=#{OAUTH_SIGNATURE_METHOD}&oauth_timestamp=#{@@timestamp}&oauth_version=#{OAUTH_VERSION}"
  puts url
  url             
end

def sign(url)
  Base64.encode64(HMAC::SHA1.digest((NONCE + url), OAUTH_CONSUMER_SECRET)).strip
end

def get_request_token
  url = generate_oauth_url
  signed_url = sign(url)          
  request = Net::HTTP.new((CONNECT_URL + REQUEST_TOKEN_PATH),80)
  puts request.inspect
  headers = { "Authorization" => "Authorization: OAuth oauth_nonce = #{NONCE}, oauth_callback = #{OAUTH_CALLBACK}, oauth_signature_meth    od = #{OAUTH_SIGNATURE_METHOD}, oauth_timestamp=#{@@timestamp}, oauth_consumer_key = #{OAUTH_CONSUMER_KEY}, oauth_signature = #{signed_url}, oauth_versio    n = #{OAUTH_VERSION}" }

  request.post(url, nil,headers)                  
end

def timestamp
  Time.now.to_i
end
Run Code Online (Sandbox Code Playgroud)

我试图做oauth的工作,试图了解如何使用Authorization标头.我也收到以下错误.我正在尝试连接到linkedin API. …

authorization oauth linkedin

9
推荐指数
2
解决办法
3万
查看次数

AMQP动态创建订阅队列

我正在尝试使用AMQP,Websockets和Ruby构建一个简单的聊天应用程序.我理解这可能不是理解AMQP的最佳用例,但我想了解我哪里出错了.

以下是我的amqp-server代码

require 'rubygems'
require 'amqp'
require 'mongo'
require 'em-websocket'
require 'json'

class MessageParser
  # message format => "room:harry_potter, nickname:siddharth, room:members"
  def self.parse(message)
    parsed_message = JSON.parse(message)

    response = {}
    if parsed_message['status'] == 'status'
      response[:status] = 'STATUS'
      response[:username] = parsed_message['username']
      response[:roomname] = parsed_message['roomname']
    elsif parsed_message['status'] == 'message'
      response[:status]   = 'MESSAGE'
      response[:message]  = parsed_message['message']
      response[:roomname] = parsed_message['roomname'].split().join('_')
    end

    response
  end
end

class MongoManager
  def self.establish_connection(database)
    @db ||= Mongo::Connection.new('localhost', 27017).db(database)
    @db.collection('rooms')

    @db
  end  
end


@sockets = []
EventMachine.run do
  connection = AMQP.connect(:host => …
Run Code Online (Sandbox Code Playgroud)

ruby amqp websocket

8
推荐指数
1
解决办法
827
查看次数

可以作为ubuntu用户连接到EC2,但不能像我创建的用户那样连接

我创建了一个新的ebs支持的EC2实例和必要的密钥对.现在我能够以ubuntu用户身份连接到实例.一旦我这样做,我创建了另一个用户并将其添加到sudoers列表,但我无法以我创建的新用户身份连接到该实例.

我收到以下错误.我使用相同的密钥连接我创建的新用户.有人可以帮助我.我在这里错过了什么吗?

Permission denied (publickey)"
Run Code Online (Sandbox Code Playgroud)

ssh amazon-ec2

7
推荐指数
1
解决办法
3215
查看次数

memcached作为Rails中的Object存储

我在我的Rails应用程序中使用Memcached作为Object Store,我在其中存储了memcached中User对象的搜索结果

现在,当我获取数据时,我得到了Memcached Undefined Class/Module Error.我在这个博客中找到了解决这个问题的方法

http://www.philsergi.com/2007/06/rails-memcached-undefinded-classmodule.html

 before_filter :preload_models
  def preload_models
    Model1
    Model2
  end
Run Code Online (Sandbox Code Playgroud)

建议事先预装模型.我想知道是否有一个更优雅的解决方案来解决这个问题,并且使用预加载技术有任何缺点.

提前致谢

memcached ruby-on-rails models eager-loading

7
推荐指数
2
解决办法
2345
查看次数

Authlogic记录方法.这是做什么的

我遇到了这种叫做记录的方法,Ryan bates在他的authlogic Railscast中使用它并且似乎无法理解它的作用.我已经阅读了文档,但我似乎无法理解该帮助程序是如何有用的.

def current_user
  return @current_user if defined?(@current_user)

  current_user_session && current_user_session.record
end
Run Code Online (Sandbox Code Playgroud)

我想知道的是,这只是从数据库中获取记录,为什么它与从数据库中获取数据的标准方式不同.

谢谢.

ruby activerecord ruby-on-rails authlogic

6
推荐指数
1
解决办法
857
查看次数