Skip to content

Commit

Permalink
search_baseの仮組み
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshimi committed May 12, 2012
1 parent 54fec24 commit dc6f78e
Show file tree
Hide file tree
Showing 25 changed files with 371 additions and 137 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -5,3 +5,4 @@ test/dummy/db/*.sqlite3
test/dummy/log/*.log test/dummy/log/*.log
test/dummy/tmp/ test/dummy/tmp/
test/dummy/.sass-cache test/dummy/.sass-cache
.DS_Store
4 changes: 4 additions & 0 deletions lib/railstar.rb
@@ -1,7 +1,11 @@
require 'railstar/engine' require 'railstar/engine'
require 'railstar/code_holder' require 'railstar/code_holder'
require 'railstar/search_base'

require 'railstar/helper' require 'railstar/helper'
ActionView::Base.send(:include, Railstar::Helper) ActionView::Base.send(:include, Railstar::Helper)
require 'railstar/active_record_ext'
ActiveRecord::Base.send(:include, Railstar::ActiveRecordExt)


module Railstar module Railstar
def self.env def self.env
Expand Down
39 changes: 39 additions & 0 deletions lib/railstar/active_record_ext.rb
@@ -0,0 +1,39 @@
# encoding: utf-8
module Railstar
module ActiveRecordExt
module ClassMethods
def truncation
return if self.count > 0
self.truncation!
end

def truncation!
table_name = self.to_s.underscore.pluralize
file_name = "#{table_name}.yml"
file_path = File.join(Rails.root, "resources", "db", file_name)
raise "#{file_path} file not found." unless File.exist?(file_path)
self.transaction do
case self.connection.adapter_name
when "SQLite"
self.connection.execute("DELETE FROM `#{self.table_name}`")
else
self.connection.execute("TRUNCATE TABLE `#{self.table_name}`")
end
YAML.load_file(file_path).each do |key, value|
self.create value
end
end
end
end

module InstanceMethods
end

def self.included(base)
base.extend ClassMethods
base.class_eval do
include InstanceMethods
end
end
end
end
92 changes: 92 additions & 0 deletions lib/railstar/search_base.rb
@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
module Railstar
class SearchBase
attr_accessor :where, :values

def initialize(hash)
self.where = []
self.values = {}
if hash
hash.each do |k,v|
send("#{k}=", v)
end
end
end

def to_params
ret = {}
TARGET_COLUMN.each do |c|
unless eval(c.to_s).blank?
ret[c] = eval(c.to_s)
end
end
return ret
end

def to_str_params
ret = to_params.map do |k,v|
begin
"#{k}=#{CGI.escape(v)}"
rescue
end
end
ret.join("&")
end

def base
create_conditions #TODO: 毎回条件作成をしないようにしたい
target_model.where([self.where.join(" AND "), values])
end

private
def like(method, options={})
value = eval(method.to_s)
unless value.blank?
column = options[:column] || method
self.where << "#{with_table_name(options[:table_name],column)} like :#{method}"
self.values[method] = "%#{value}%"
end
end

def eq(method, options={})
compare(method, "=", options)
end

def inc(method, options={})
value = eval(method.to_s)
value = value.split(",") if value.is_a?(String) && value.include?(",")
unless value.blank?
column = options[:column] || method
self.where << "#{with_table_name(options[:table_name],column)} in (:#{method})"
self.values[method] = value
end
end

def compare(method, sign, options={})
return unless sign =~ /^[<>=]{1,2}$/
value = eval(method.to_s)
unless value.blank?
column = options[:column] || method
self.where << "#{with_table_name(options[:table_name],column)} #{sign} :#{method}"
self.values[method] = value
end
end

def bit(method, options={})
value = eval(method.to_s)
unless value.blank?
column = options[:column] || method
self.where << "#{with_table_name(options[:table_name],column)} & :#{method} = :#{method}"
self.values[method] = value
end
end


def with_table_name table_name, method
ret = ""
ret << "#{table_name || target_model.table_name}." if table_name
ret << method.to_s
ret
end
end
end
3 changes: 2 additions & 1 deletion test/dummy/app/controllers/projects_controller.rb
Expand Up @@ -5,7 +5,8 @@


class ProjectsController < ApplicationController class ProjectsController < ApplicationController
def index def index
@projects = Project.order("created_at desc").all @search = Search::Project.new(params[:search])
@projects = @search.base.joins("inner join tasks on tasks.project_id = projects.id").order("created_at desc").group("projects.id").all
end end


def show def show
Expand Down
86 changes: 32 additions & 54 deletions test/dummy/app/controllers/tasks_controller.rb
@@ -1,83 +1,61 @@
# -*- coding: utf-8 -*-
# destroyメソッドに注意。モバイル対応&テキストリンク利用のためイレギュラーなことをしている
# restに対応した形を徹底したい場合は、削除確認ページへのリンクを以下の様に、formにする
# <%= form_tag(Task_path(task, :mode => "draft"), :method=>:delete) do %><%= submit_tag "delete", :name => "delete" %><% end %>

class TasksController < ApplicationController class TasksController < ApplicationController
# GET /tasks
# GET /tasks.json
def index def index
@tasks = Task.all @search = Search::Task.new(params[:search])

@search.project_id = params[:project_id]
respond_to do |format| @tasks = @search.base.order("created_at desc").all
format.html # index.html.erb
format.json { render json: @tasks }
end
end end


# GET /tasks/1
# GET /tasks/1.json
def show def show
@task = Task.find(params[:id]) @task = Task.find(params[:id])

render "destroy" if params[:mode] == "draft"
respond_to do |format|
format.html # show.html.erb
format.json { render json: @task }
end
end end


# GET /tasks/new
# GET /tasks/new.json
def new def new
@task = Task.new @task = Task.new(params[:task])

respond_to do |format|
format.html # new.html.erb
format.json { render json: @task }
end
end end


# GET /tasks/1/edit
def edit def edit
@task = Task.find(params[:id]) @task = Task.find(params[:id])
end end


# POST /tasks
# POST /tasks.json
def create def create
@task = Task.new(params[:task]) @task = Task.new(params[:task])

save
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render json: @task, status: :created, location: @task }
else
format.html { render action: "new" }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end end


# PUT /tasks/1
# PUT /tasks/1.json
def update def update
@task = Task.find(params[:id]) @task = Task.find(params[:id])

@task.attributes = params[:task]
respond_to do |format| save
if @task.update_attributes(params[:task])
format.html { redirect_to @task, notice: 'Task was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end end


# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy def destroy
@task = Task.find(params[:id]) @task = Task.find(params[:id])
@task.destroy if params.key?("back")
redirect_to(task_url)
elsif params[:mode] != "draft"
@task.destroy
redirect_to(task_url, :notice => "deleted success.")
end
end


respond_to do |format|
format.html { redirect_to tasks_url } private
format.json { head :no_content } def save
if !params.key?("back") && @task.valid?
if params[:mode] == "draft"
render :action => 'confirm'
else
@task.save!
redirect_to task_path(@task), :notice => 'saved success.'
end
else
render (@task.new_record? ? :new : :edit)
end end
end end
end end
14 changes: 14 additions & 0 deletions test/dummy/app/models/search/project.rb
@@ -0,0 +1,14 @@
class Search::Project < Railstar::SearchBase
TARGET_COLUMN = %w(name like_name)
attr_accessor *TARGET_COLUMN

private
def create_conditions
eq(:name)
like(:like_name, column: :name, table_name: "tasks")
end

def target_model
::Project
end
end
18 changes: 18 additions & 0 deletions test/dummy/app/models/search/task.rb
@@ -0,0 +1,18 @@
class Search::Task < Railstar::SearchBase
TARGET_COLUMN = %w(name like_name status project_id from_price to_price)
attr_accessor *TARGET_COLUMN

private
def create_conditions
eq(:project_id)
eq(:name)
like(:like_name, column: :name)
inc(:status)
compare(:from_price, ">=", column: :price)
compare(:to_price, "<=", column: :price)
end

def target_model
::Task
end
end
3 changes: 2 additions & 1 deletion test/dummy/app/views/general/index.html.erb
@@ -1 +1,2 @@
<%= link_to "Railstar", railstar.root_path %> <%= link_to "Railstar", railstar.root_path %><br />
<%= link_to "TestProject", projects_path %><br />
15 changes: 10 additions & 5 deletions test/dummy/app/views/projects/index.html.erb
@@ -1,10 +1,16 @@
<h1>Listing projects</h1> <h1>Listing projects</h1>


<%= form_tag(nil, :method => :get) do %>
<%= label :search, :name %>:<%= text_field :search, :name %><br />
<%= label :search, :like_name %>:<%= text_field :search, :like_name %><br />
<%= submit_tag :search %>
<% end %>

<table> <table>
<thead> <thead>
<tr> <tr>
<th>Name</th> <th>Name</th>
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
</tr> </tr>
Expand All @@ -14,9 +20,8 @@
<tbody> <tbody>
<% @projects.each do |project| %> <% @projects.each do |project| %>
<tr> <tr>
<th>Name</th> <td><%= link_to project.name, project_tasks_path(:project_id => project.id) %></td>
<td><%= project.name %></td> <td><%= link_to 'Show', project %></td>
<td><%= link_to 'Show', project %></td>
<td><%= link_to 'Edit', edit_project_path(project) %></td> <td><%= link_to 'Edit', edit_project_path(project) %></td>
<td><%= link_to 'Delete', project_path(project, :mode => "draft") %></td> <td><%= link_to 'Delete', project_path(project, :mode => "draft") %></td>
</tr> </tr>
Expand Down
8 changes: 8 additions & 0 deletions test/dummy/app/views/tasks/_detail.html.erb
@@ -0,0 +1,8 @@
<table class="bordered-table zebra-striped">

<tr>
<th>Name</th>
<td><%= @task.name %></td>
</tr>

</table>
40 changes: 14 additions & 26 deletions test/dummy/app/views/tasks/_form.html.erb
@@ -1,29 +1,17 @@
<%= form_for(@task) do |f| %> <%= form_for(@task, :url => save_action(@task, :mode => "draft")) do |f| %>
<% if @task.errors.any? %> <% if @task.errors.any? %>
<div id="error_explanation"> <% @task.errors.full_messages.each do |msg| %>
<h2><%= pluralize(@task.errors.count, "error") %> prohibited this task from being saved:</h2> <p><%= msg %></p>
<% end %>
<% end %>



<ul> <table class="bordered-table zebra-striped">
<% @task.errors.full_messages.each do |msg| %> <tr>
<li><%= msg %></li> <th><%= f.label :name %></th>
<% end %> <td><%= f.text_field :name %></td>
</ul> </tr>
</div> </table>
<% end %>


<div class="field"> <%= f.submit :class => "btn primary" %>
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :project_id %><br />
<%= f.number_field :project_id %>
</div>
<div class="field">
<%= f.label :status %><br />
<%= f.number_field :status %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %> <% end %>

0 comments on commit dc6f78e

Please sign in to comment.