Bài đăng

Hiển thị các bài đăng có nhãn Rails

Regular Expression in Ruby

In this post, I intend to write down some basic Regex knowledge, especially for Ruby. Syntax A regular expression literal is a pattern between slashes or between arbitrary delimiters followed by %r as follows: /pattern/ /pattern/im # option can be specified %r!/usr/local! # general delimited regular expression Basic patterns Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \ ), all characters match themselves. You can escape a control character by preceding it with a backslash. Following table lists the regular expression syntax that is available in Ruby. Patterns Description ^ Matches beginning of line. $ Matches end of line. . Matches any single character except newline. Using m option to allow it to match newline as well. […] Matches any single character in brackets. [^…] Matches any single character not in brackets re* Matches 0 or more occurrences of preceding expression. re+ Matches 1 or more occurrence of preceding expression. re? ...

Beautiful controller in Ruby on Rails

Your controllers is too fat and messy. You want to make them better. You should be follow these rules: Short, DRY, easy to read Minimum amount of glue code between request and model Unless there is good reason, controller should be follow a standard When user’s interactions are normalized to CRUD. Our controller could be like this class ObjectController < ApplicationController def index load_objects end def show load_object end def new build_object end def create build_object save or render 'new' end def edit load_object build_object end def update load_object build_object save or render 'edit' end def destroy load_object @object . destroy redirect_to objects_path end private def object_params obj_params = params [ :object ] obj_params ? obj_params . permit ( :id , :attributes ) : {} end def loa...

3 common security issues in Rails

SQL injection Đây là kiểu tấn công gây ảnh hưởng lên câu truy vấn dữ liệu thông qua các tham số của ứng dụng web. Thường thì chúng được dùng để vượt qua bước chứng thực hay để đánh cắp dữ liệu. Ví dụ bạn muốn tìm những project có tên được lấy từ tham số name: Project.where("name = '#{params[:name]}'") Tham số này có thể là  'OR 1 -- . Kết quả câu truy vấn là: SELECT * FROM projects WHERE name = '' OR 1 --' (trả về là tất cả projects). Hay nếu tham số là ') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users -- thì câu truy vấn dữ liệu là: SELECT * FROM projects WHERE (name = '') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --'  (lấy name và password của tất cả users). Cách phòng chống: Ruby on Rails đã xây dựng 1 filter để lọc các ký tự đặc biệt trong SQL:  ' ,  " ,  null  và xuống dòng. Filter này được dùng tự động cho câu lệnh  find  hay  find_by_something . V...