RUBY实践—带密码加密的用户创建及修改
开发环境
Ruby: Ruby1.9.1
Rails: Rails2.3.5
Mysql:Mysql5.0.9
Driver:mysql-2.8.1-x86-mingw32.gem
IDE:Rubymine2.0.1
一、创建数据表Users
利用RubyMine自带的Scaffold工具创建数据表Users,也可以手动创建
二、创建Controller和View
Ruby项目—>右键—>Create Model
完成后将自动生成相应的文件
三、修改Model user.rb
利用Digest/SHA1对密码进行加密,实现加密保存
修改后代码如下:
require "digest/sha1"
class User < ActiveRecord::Base
attr_accessor :hashed_password,:repassword
attr_accessible :username, :hashed_password, :repassword
validates_uniqueness_of :username
validates_presence_of :username, :hashed_password
def before_create
self.password = User.hash_password(self.hashed_password)
end
def after_create
@hashed_password = nil
end
def before_update
self.password = User.hash_password(self.hashed_password)
end
def after_update
@hashed_password = nil
end
private
def self.hash_password(hashed_password)
Digest::SHA1.hexdigest(hashed_password)
end
end
四、修改users_controller.rb
修改update方法,实现当进行edit操作时先判断password与 password_confirm是否一致,
如果一致,则进行update操作,否则提示用户password 与 password_confirm 输入不一致
修改后代码如下:
def update
@user = User.find(params[:id])
respond_to do |format|
print "user: #{params[:user]}"
if params[:user]["hashed_password"] == params[:user]["repassword"]
if @user.update_attributes(params[:user])
flash[:notice] = 'User was successfully updated.'
format.html { redirect_to(@user) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
else
flash[:notice] = 'Password and Password confirm are not the same'
format.html { render :action => "edit" }
format.xml
相关文档:
self上下文
Ruby的self有和Java的this相似之处,但又大不相同。Java的方法都是在实例方法中引用,所以this一般都是指向当前对象的。而Ruby的代码逐行执行,所以在不同的上下文(context)self就有了不同的含义,先来看看常见的context self都代表哪些
1
2
3
4
5
6
7
8
9
10
11
12
13
......
class Point
@x = 1
@y = 2
def initialize(x,y)
@x,@y = x,y
end
end
代码中的@x,@y为实例变量,实例变量只对self的环境起作用,因此initialize外面的@x=1,@y=2只对类本身起作用,而方法内部,的@x,@y是对对象的实例起作用的。
class Point
include Enumerable
def initialize(x ......
使用 will_paginate 进行分页和简单查询
在命令行下使用 gem install will_paginate 命令,出现下面结果安装成功
打开 books_controller.rb (你自己的控制器)
注释掉查找全部的方法,使用下面的方法,已经集成根据title进行查询
Ruby代码
#@books = Book.all
@books = Book.pagina ......
ruby常规访问access数据库的方法应该是使用DBI库
:
require 'dbi'
DBI.connect("DBI:ADO:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb;")
可是
简单尝试之后没能成功,提示找不到驱动器ADO,懒得再试,遂找其他方法。
一番搜索之后,发现可以用WIN32OLE来访问access,写一个简单的类包装之:
......