如何从Sequel模型访问Sinatra params hash并设置Sinatra会话哈希?

时间:2016-06-14 14:38:28

标签: ruby hash sinatra sequel

基本上我试图将此处的代码移植到Sinatra和Sequel:How to use bcrypt() in your Rails application

事实上,我正在尝试在Sequel User模型中编写简单的注册和登录方法,目前看起来像这样:

require 'sequel'
require 'bcrypt'

USERNAME_REGEXP = /^(\w){1,32}$/

# This file is called user.rb and it contains the User class, adding custom
# behavior to 'users' dataset by following its business logic.
class User < Sequel::Model(:users)
  include BCrypt

  one_to_many :items
  one_to_many :reactions

  plugin :validation_helpers

  def validate
    super
    validates_unique(:username, :email)
    validates_presence([:username, :password, :email])
    validates_format(USERNAME_REGEXP, :username)
  end

  def password
    @password ||= Password.new(password_hash)
  end

  def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
  end

  def signup(params = {})
    @user = User.new(username: params[:username], email: params[:email])
    @user.password = params[:password]
    @user.save
  end

  def login(params = {})
    @user = User.where(username: params[:username], delete: false).first
    if @user.password == params[:password]
      session[:user_id] = @user.id
      redirect to("/#{@user.username}")
    else
      redirect to('/login')
    end
  end
end

然后我的Sinatra app.rb需要续集用户模型 - 所以我的问题是:我可以通过这种方式访问​​paramssession,而不需要模型中的Sinatra吗?

非常感谢您的帮助!

0 个答案:

没有答案