Merged trunk r1773.
git-svn-id: http://redmine.rubyforge.org/svn/branches/work@1774 e93f8b46-1217-0410-a6f0-8f06a7374b81
This commit is contained in:
@@ -25,14 +25,15 @@ module Redmine
|
||||
module ClassMethods
|
||||
def acts_as_event(options = {})
|
||||
return if self.included_modules.include?(Redmine::Acts::Event::InstanceMethods)
|
||||
options[:datetime] ||= :created_on
|
||||
options[:title] ||= :title
|
||||
options[:description] ||= :description
|
||||
options[:author] ||= :author
|
||||
options[:url] ||= {:controller => 'welcome'}
|
||||
options[:type] ||= self.name.underscore.dasherize
|
||||
default_options = { :datetime => :created_on,
|
||||
:title => :title,
|
||||
:description => :description,
|
||||
:author => :author,
|
||||
:url => {:controller => 'welcome'},
|
||||
:type => self.name.underscore.dasherize }
|
||||
|
||||
cattr_accessor :event_options
|
||||
self.event_options = options
|
||||
self.event_options = default_options.merge(options)
|
||||
send :include, Redmine::Acts::Event::InstanceMethods
|
||||
end
|
||||
end
|
||||
|
||||
@@ -23,6 +23,12 @@ module Redmine
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
# Options:
|
||||
# * :columns - a column or an array of columns to search
|
||||
# * :project_key - project foreign key (default to project_id)
|
||||
# * :date_column - name of the datetime column (default to created_on)
|
||||
# * :sort_order - name of the column used to sort results (default to :date_column or created_on)
|
||||
# * :permission - permission required to search the model (default to :view_"objects")
|
||||
def acts_as_searchable(options = {})
|
||||
return if self.included_modules.include?(Redmine::Acts::Searchable::InstanceMethods)
|
||||
|
||||
@@ -35,19 +41,12 @@ module Redmine
|
||||
searchable_options[:columns] = [] << searchable_options[:columns]
|
||||
end
|
||||
|
||||
if searchable_options[:project_key]
|
||||
elsif column_names.include?('project_id')
|
||||
searchable_options[:project_key] = "#{table_name}.project_id"
|
||||
else
|
||||
raise 'No project key defined.'
|
||||
end
|
||||
searchable_options[:project_key] ||= "#{table_name}.project_id"
|
||||
searchable_options[:date_column] ||= "#{table_name}.created_on"
|
||||
searchable_options[:order_column] ||= searchable_options[:date_column]
|
||||
|
||||
if searchable_options[:date_column]
|
||||
elsif column_names.include?('created_on')
|
||||
searchable_options[:date_column] = "#{table_name}.created_on"
|
||||
else
|
||||
raise 'No date column defined defined.'
|
||||
end
|
||||
# Permission needed to search this model
|
||||
searchable_options[:permission] = "view_#{self.name.underscore.pluralize}".to_sym unless searchable_options.has_key?(:permission)
|
||||
|
||||
# Should we search custom fields on this model ?
|
||||
searchable_options[:search_custom_fields] = !reflect_on_association(:custom_values).nil?
|
||||
@@ -62,13 +61,24 @@ module Redmine
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
def search(tokens, project, options={})
|
||||
# Searches the model for the given tokens
|
||||
# projects argument can be either nil (will search all projects), a project or an array of projects
|
||||
# Returns the results and the results count
|
||||
def search(tokens, projects=nil, options={})
|
||||
tokens = [] << tokens unless tokens.is_a?(Array)
|
||||
projects = [] << projects unless projects.nil? || projects.is_a?(Array)
|
||||
|
||||
find_options = {:include => searchable_options[:include]}
|
||||
find_options[:limit] = options[:limit] if options[:limit]
|
||||
find_options[:order] = "#{searchable_options[:date_column]} " + (options[:before] ? 'DESC' : 'ASC')
|
||||
find_options[:order] = "#{searchable_options[:order_column]} " + (options[:before] ? 'DESC' : 'ASC')
|
||||
|
||||
limit_options = {}
|
||||
limit_options[:limit] = options[:limit] if options[:limit]
|
||||
if options[:offset]
|
||||
limit_options[:conditions] = "(#{searchable_options[:date_column]} " + (options[:before] ? '<' : '>') + "'#{connection.quoted_date(options[:offset])}')"
|
||||
end
|
||||
|
||||
columns = searchable_options[:columns]
|
||||
columns.slice!(1..-1) if options[:titles_only]
|
||||
columns = columns[0..0] if options[:titles_only]
|
||||
|
||||
token_clauses = columns.collect {|column| "(LOWER(#{column}) LIKE ?)"}
|
||||
|
||||
@@ -87,21 +97,23 @@ module Redmine
|
||||
|
||||
sql = (['(' + token_clauses.join(' OR ') + ')'] * tokens.size).join(options[:all_words] ? ' AND ' : ' OR ')
|
||||
|
||||
if options[:offset]
|
||||
sql = "(#{sql}) AND (#{searchable_options[:date_column]} " + (options[:before] ? '<' : '>') + "'#{connection.quoted_date(options[:offset])}')"
|
||||
end
|
||||
find_options[:conditions] = [sql, * (tokens * token_clauses.size).sort]
|
||||
|
||||
results = with_scope(:find => {:conditions => ["#{searchable_options[:project_key]} = ?", project.id]}) do
|
||||
find(:all, find_options)
|
||||
end
|
||||
if searchable_options[:with] && !options[:titles_only]
|
||||
searchable_options[:with].each do |model, assoc|
|
||||
results += model.to_s.camelcase.constantize.search(tokens, project, options).collect {|r| r.send assoc}
|
||||
project_conditions = []
|
||||
project_conditions << (searchable_options[:permission].nil? ? Project.visible_by(User.current) :
|
||||
Project.allowed_to_condition(User.current, searchable_options[:permission]))
|
||||
project_conditions << "#{searchable_options[:project_key]} IN (#{projects.collect(&:id).join(',')})" unless projects.nil?
|
||||
|
||||
results = []
|
||||
results_count = 0
|
||||
|
||||
with_scope(:find => {:conditions => project_conditions.join(' AND ')}) do
|
||||
with_scope(:find => find_options) do
|
||||
results_count = count(:all)
|
||||
results = find(:all, limit_options)
|
||||
end
|
||||
results.uniq!
|
||||
end
|
||||
results
|
||||
[results, results_count]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -70,6 +70,13 @@ module ActiveRecord
|
||||
nodes
|
||||
end
|
||||
|
||||
# Returns list of descendants.
|
||||
#
|
||||
# root.descendants # => [child1, subchild1, subchild2]
|
||||
def descendants
|
||||
children + children.collect(&:children).flatten
|
||||
end
|
||||
|
||||
# Returns the root node of the tree.
|
||||
def root
|
||||
node = self
|
||||
|
||||
+181
-181
@@ -1,182 +1,182 @@
|
||||
require 'rubygems'
|
||||
|
||||
Gem::manage_gems
|
||||
|
||||
require 'rake/rdoctask'
|
||||
require 'rake/packagetask'
|
||||
require 'rake/gempackagetask'
|
||||
require 'rake/testtask'
|
||||
require 'rake/contrib/rubyforgepublisher'
|
||||
|
||||
PKG_NAME = 'acts_as_versioned'
|
||||
PKG_VERSION = '0.3.1'
|
||||
PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
|
||||
PROD_HOST = "technoweenie@bidwell.textdrive.com"
|
||||
RUBY_FORGE_PROJECT = 'ar-versioned'
|
||||
RUBY_FORGE_USER = 'technoweenie'
|
||||
|
||||
desc 'Default: run unit tests.'
|
||||
task :default => :test
|
||||
|
||||
desc 'Test the calculations plugin.'
|
||||
Rake::TestTask.new(:test) do |t|
|
||||
t.libs << 'lib'
|
||||
t.pattern = 'test/**/*_test.rb'
|
||||
t.verbose = true
|
||||
end
|
||||
|
||||
desc 'Generate documentation for the calculations plugin.'
|
||||
Rake::RDocTask.new(:rdoc) do |rdoc|
|
||||
rdoc.rdoc_dir = 'rdoc'
|
||||
rdoc.title = "#{PKG_NAME} -- Simple versioning with active record models"
|
||||
rdoc.options << '--line-numbers --inline-source'
|
||||
rdoc.rdoc_files.include('README', 'CHANGELOG', 'RUNNING_UNIT_TESTS')
|
||||
rdoc.rdoc_files.include('lib/**/*.rb')
|
||||
end
|
||||
|
||||
spec = Gem::Specification.new do |s|
|
||||
s.name = PKG_NAME
|
||||
s.version = PKG_VERSION
|
||||
s.platform = Gem::Platform::RUBY
|
||||
s.summary = "Simple versioning with active record models"
|
||||
s.files = FileList["{lib,test}/**/*"].to_a + %w(README MIT-LICENSE CHANGELOG RUNNING_UNIT_TESTS)
|
||||
s.files.delete "acts_as_versioned_plugin.sqlite.db"
|
||||
s.files.delete "acts_as_versioned_plugin.sqlite3.db"
|
||||
s.files.delete "test/debug.log"
|
||||
s.require_path = 'lib'
|
||||
s.autorequire = 'acts_as_versioned'
|
||||
s.has_rdoc = true
|
||||
s.test_files = Dir['test/**/*_test.rb']
|
||||
s.add_dependency 'activerecord', '>= 1.10.1'
|
||||
s.add_dependency 'activesupport', '>= 1.1.1'
|
||||
s.author = "Rick Olson"
|
||||
s.email = "technoweenie@gmail.com"
|
||||
s.homepage = "http://techno-weenie.net"
|
||||
end
|
||||
|
||||
Rake::GemPackageTask.new(spec) do |pkg|
|
||||
pkg.need_tar = true
|
||||
end
|
||||
|
||||
desc "Publish the API documentation"
|
||||
task :pdoc => [:rdoc] do
|
||||
Rake::RubyForgePublisher.new(RUBY_FORGE_PROJECT, RUBY_FORGE_USER).upload
|
||||
end
|
||||
|
||||
desc 'Publish the gem and API docs'
|
||||
task :publish => [:pdoc, :rubyforge_upload]
|
||||
|
||||
desc "Publish the release files to RubyForge."
|
||||
task :rubyforge_upload => :package do
|
||||
files = %w(gem tgz).map { |ext| "pkg/#{PKG_FILE_NAME}.#{ext}" }
|
||||
|
||||
if RUBY_FORGE_PROJECT then
|
||||
require 'net/http'
|
||||
require 'open-uri'
|
||||
|
||||
project_uri = "http://rubyforge.org/projects/#{RUBY_FORGE_PROJECT}/"
|
||||
project_data = open(project_uri) { |data| data.read }
|
||||
group_id = project_data[/[?&]group_id=(\d+)/, 1]
|
||||
raise "Couldn't get group id" unless group_id
|
||||
|
||||
# This echos password to shell which is a bit sucky
|
||||
if ENV["RUBY_FORGE_PASSWORD"]
|
||||
password = ENV["RUBY_FORGE_PASSWORD"]
|
||||
else
|
||||
print "#{RUBY_FORGE_USER}@rubyforge.org's password: "
|
||||
password = STDIN.gets.chomp
|
||||
end
|
||||
|
||||
login_response = Net::HTTP.start("rubyforge.org", 80) do |http|
|
||||
data = [
|
||||
"login=1",
|
||||
"form_loginname=#{RUBY_FORGE_USER}",
|
||||
"form_pw=#{password}"
|
||||
].join("&")
|
||||
http.post("/account/login.php", data)
|
||||
end
|
||||
|
||||
cookie = login_response["set-cookie"]
|
||||
raise "Login failed" unless cookie
|
||||
headers = { "Cookie" => cookie }
|
||||
|
||||
release_uri = "http://rubyforge.org/frs/admin/?group_id=#{group_id}"
|
||||
release_data = open(release_uri, headers) { |data| data.read }
|
||||
package_id = release_data[/[?&]package_id=(\d+)/, 1]
|
||||
raise "Couldn't get package id" unless package_id
|
||||
|
||||
first_file = true
|
||||
release_id = ""
|
||||
|
||||
files.each do |filename|
|
||||
basename = File.basename(filename)
|
||||
file_ext = File.extname(filename)
|
||||
file_data = File.open(filename, "rb") { |file| file.read }
|
||||
|
||||
puts "Releasing #{basename}..."
|
||||
|
||||
release_response = Net::HTTP.start("rubyforge.org", 80) do |http|
|
||||
release_date = Time.now.strftime("%Y-%m-%d %H:%M")
|
||||
type_map = {
|
||||
".zip" => "3000",
|
||||
".tgz" => "3110",
|
||||
".gz" => "3110",
|
||||
".gem" => "1400"
|
||||
}; type_map.default = "9999"
|
||||
type = type_map[file_ext]
|
||||
boundary = "rubyqMY6QN9bp6e4kS21H4y0zxcvoor"
|
||||
|
||||
query_hash = if first_file then
|
||||
{
|
||||
"group_id" => group_id,
|
||||
"package_id" => package_id,
|
||||
"release_name" => PKG_FILE_NAME,
|
||||
"release_date" => release_date,
|
||||
"type_id" => type,
|
||||
"processor_id" => "8000", # Any
|
||||
"release_notes" => "",
|
||||
"release_changes" => "",
|
||||
"preformatted" => "1",
|
||||
"submit" => "1"
|
||||
}
|
||||
else
|
||||
{
|
||||
"group_id" => group_id,
|
||||
"release_id" => release_id,
|
||||
"package_id" => package_id,
|
||||
"step2" => "1",
|
||||
"type_id" => type,
|
||||
"processor_id" => "8000", # Any
|
||||
"submit" => "Add This File"
|
||||
}
|
||||
end
|
||||
|
||||
query = "?" + query_hash.map do |(name, value)|
|
||||
[name, URI.encode(value)].join("=")
|
||||
end.join("&")
|
||||
|
||||
data = [
|
||||
"--" + boundary,
|
||||
"Content-Disposition: form-data; name=\"userfile\"; filename=\"#{basename}\"",
|
||||
"Content-Type: application/octet-stream",
|
||||
"Content-Transfer-Encoding: binary",
|
||||
"", file_data, ""
|
||||
].join("\x0D\x0A")
|
||||
|
||||
release_headers = headers.merge(
|
||||
"Content-Type" => "multipart/form-data; boundary=#{boundary}"
|
||||
)
|
||||
|
||||
target = first_file ? "/frs/admin/qrs.php" : "/frs/admin/editrelease.php"
|
||||
http.post(target + query, data, release_headers)
|
||||
end
|
||||
|
||||
if first_file then
|
||||
release_id = release_response.body[/release_id=(\d+)/, 1]
|
||||
raise("Couldn't get release id") unless release_id
|
||||
end
|
||||
|
||||
first_file = false
|
||||
end
|
||||
end
|
||||
require 'rubygems'
|
||||
|
||||
Gem::manage_gems
|
||||
|
||||
require 'rake/rdoctask'
|
||||
require 'rake/packagetask'
|
||||
require 'rake/gempackagetask'
|
||||
require 'rake/testtask'
|
||||
require 'rake/contrib/rubyforgepublisher'
|
||||
|
||||
PKG_NAME = 'acts_as_versioned'
|
||||
PKG_VERSION = '0.3.1'
|
||||
PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
|
||||
PROD_HOST = "technoweenie@bidwell.textdrive.com"
|
||||
RUBY_FORGE_PROJECT = 'ar-versioned'
|
||||
RUBY_FORGE_USER = 'technoweenie'
|
||||
|
||||
desc 'Default: run unit tests.'
|
||||
task :default => :test
|
||||
|
||||
desc 'Test the calculations plugin.'
|
||||
Rake::TestTask.new(:test) do |t|
|
||||
t.libs << 'lib'
|
||||
t.pattern = 'test/**/*_test.rb'
|
||||
t.verbose = true
|
||||
end
|
||||
|
||||
desc 'Generate documentation for the calculations plugin.'
|
||||
Rake::RDocTask.new(:rdoc) do |rdoc|
|
||||
rdoc.rdoc_dir = 'rdoc'
|
||||
rdoc.title = "#{PKG_NAME} -- Simple versioning with active record models"
|
||||
rdoc.options << '--line-numbers --inline-source'
|
||||
rdoc.rdoc_files.include('README', 'CHANGELOG', 'RUNNING_UNIT_TESTS')
|
||||
rdoc.rdoc_files.include('lib/**/*.rb')
|
||||
end
|
||||
|
||||
spec = Gem::Specification.new do |s|
|
||||
s.name = PKG_NAME
|
||||
s.version = PKG_VERSION
|
||||
s.platform = Gem::Platform::RUBY
|
||||
s.summary = "Simple versioning with active record models"
|
||||
s.files = FileList["{lib,test}/**/*"].to_a + %w(README MIT-LICENSE CHANGELOG RUNNING_UNIT_TESTS)
|
||||
s.files.delete "acts_as_versioned_plugin.sqlite.db"
|
||||
s.files.delete "acts_as_versioned_plugin.sqlite3.db"
|
||||
s.files.delete "test/debug.log"
|
||||
s.require_path = 'lib'
|
||||
s.autorequire = 'acts_as_versioned'
|
||||
s.has_rdoc = true
|
||||
s.test_files = Dir['test/**/*_test.rb']
|
||||
s.add_dependency 'activerecord', '>= 1.10.1'
|
||||
s.add_dependency 'activesupport', '>= 1.1.1'
|
||||
s.author = "Rick Olson"
|
||||
s.email = "technoweenie@gmail.com"
|
||||
s.homepage = "http://techno-weenie.net"
|
||||
end
|
||||
|
||||
Rake::GemPackageTask.new(spec) do |pkg|
|
||||
pkg.need_tar = true
|
||||
end
|
||||
|
||||
desc "Publish the API documentation"
|
||||
task :pdoc => [:rdoc] do
|
||||
Rake::RubyForgePublisher.new(RUBY_FORGE_PROJECT, RUBY_FORGE_USER).upload
|
||||
end
|
||||
|
||||
desc 'Publish the gem and API docs'
|
||||
task :publish => [:pdoc, :rubyforge_upload]
|
||||
|
||||
desc "Publish the release files to RubyForge."
|
||||
task :rubyforge_upload => :package do
|
||||
files = %w(gem tgz).map { |ext| "pkg/#{PKG_FILE_NAME}.#{ext}" }
|
||||
|
||||
if RUBY_FORGE_PROJECT then
|
||||
require 'net/http'
|
||||
require 'open-uri'
|
||||
|
||||
project_uri = "http://rubyforge.org/projects/#{RUBY_FORGE_PROJECT}/"
|
||||
project_data = open(project_uri) { |data| data.read }
|
||||
group_id = project_data[/[?&]group_id=(\d+)/, 1]
|
||||
raise "Couldn't get group id" unless group_id
|
||||
|
||||
# This echos password to shell which is a bit sucky
|
||||
if ENV["RUBY_FORGE_PASSWORD"]
|
||||
password = ENV["RUBY_FORGE_PASSWORD"]
|
||||
else
|
||||
print "#{RUBY_FORGE_USER}@rubyforge.org's password: "
|
||||
password = STDIN.gets.chomp
|
||||
end
|
||||
|
||||
login_response = Net::HTTP.start("rubyforge.org", 80) do |http|
|
||||
data = [
|
||||
"login=1",
|
||||
"form_loginname=#{RUBY_FORGE_USER}",
|
||||
"form_pw=#{password}"
|
||||
].join("&")
|
||||
http.post("/account/login.php", data)
|
||||
end
|
||||
|
||||
cookie = login_response["set-cookie"]
|
||||
raise "Login failed" unless cookie
|
||||
headers = { "Cookie" => cookie }
|
||||
|
||||
release_uri = "http://rubyforge.org/frs/admin/?group_id=#{group_id}"
|
||||
release_data = open(release_uri, headers) { |data| data.read }
|
||||
package_id = release_data[/[?&]package_id=(\d+)/, 1]
|
||||
raise "Couldn't get package id" unless package_id
|
||||
|
||||
first_file = true
|
||||
release_id = ""
|
||||
|
||||
files.each do |filename|
|
||||
basename = File.basename(filename)
|
||||
file_ext = File.extname(filename)
|
||||
file_data = File.open(filename, "rb") { |file| file.read }
|
||||
|
||||
puts "Releasing #{basename}..."
|
||||
|
||||
release_response = Net::HTTP.start("rubyforge.org", 80) do |http|
|
||||
release_date = Time.now.strftime("%Y-%m-%d %H:%M")
|
||||
type_map = {
|
||||
".zip" => "3000",
|
||||
".tgz" => "3110",
|
||||
".gz" => "3110",
|
||||
".gem" => "1400"
|
||||
}; type_map.default = "9999"
|
||||
type = type_map[file_ext]
|
||||
boundary = "rubyqMY6QN9bp6e4kS21H4y0zxcvoor"
|
||||
|
||||
query_hash = if first_file then
|
||||
{
|
||||
"group_id" => group_id,
|
||||
"package_id" => package_id,
|
||||
"release_name" => PKG_FILE_NAME,
|
||||
"release_date" => release_date,
|
||||
"type_id" => type,
|
||||
"processor_id" => "8000", # Any
|
||||
"release_notes" => "",
|
||||
"release_changes" => "",
|
||||
"preformatted" => "1",
|
||||
"submit" => "1"
|
||||
}
|
||||
else
|
||||
{
|
||||
"group_id" => group_id,
|
||||
"release_id" => release_id,
|
||||
"package_id" => package_id,
|
||||
"step2" => "1",
|
||||
"type_id" => type,
|
||||
"processor_id" => "8000", # Any
|
||||
"submit" => "Add This File"
|
||||
}
|
||||
end
|
||||
|
||||
query = "?" + query_hash.map do |(name, value)|
|
||||
[name, URI.encode(value)].join("=")
|
||||
end.join("&")
|
||||
|
||||
data = [
|
||||
"--" + boundary,
|
||||
"Content-Disposition: form-data; name=\"userfile\"; filename=\"#{basename}\"",
|
||||
"Content-Type: application/octet-stream",
|
||||
"Content-Transfer-Encoding: binary",
|
||||
"", file_data, ""
|
||||
].join("\x0D\x0A")
|
||||
|
||||
release_headers = headers.merge(
|
||||
"Content-Type" => "multipart/form-data; boundary=#{boundary}"
|
||||
)
|
||||
|
||||
target = first_file ? "/frs/admin/qrs.php" : "/frs/admin/editrelease.php"
|
||||
http.post(target + query, data, release_headers)
|
||||
end
|
||||
|
||||
if first_file then
|
||||
release_id = release_response.body[/release_id=(\d+)/, 1]
|
||||
raise("Couldn't get release id") unless release_id
|
||||
end
|
||||
|
||||
first_file = false
|
||||
end
|
||||
end
|
||||
end
|
||||
+124
-71
@@ -22,7 +22,7 @@
|
||||
module ActiveRecord #:nodoc:
|
||||
module Acts #:nodoc:
|
||||
# Specify this act if you want to save a copy of the row in a versioned table. This assumes there is a
|
||||
# versioned table ready and that your model has a version field. This works with optimisic locking if the lock_version
|
||||
# versioned table ready and that your model has a version field. This works with optimistic locking if the lock_version
|
||||
# column is present as well.
|
||||
#
|
||||
# The class for the versioned model is derived the first time it is seen. Therefore, if you change your database schema you have to restart
|
||||
@@ -49,9 +49,24 @@ module ActiveRecord #:nodoc:
|
||||
# page.revert_to(page.versions.last) # using versioned instance
|
||||
# page.title # => 'hello world'
|
||||
#
|
||||
# page.versions.earliest # efficient query to find the first version
|
||||
# page.versions.latest # efficient query to find the most recently created version
|
||||
#
|
||||
#
|
||||
# Simple Queries to page between versions
|
||||
#
|
||||
# page.versions.before(version)
|
||||
# page.versions.after(version)
|
||||
#
|
||||
# Access the previous/next versions from the versioned model itself
|
||||
#
|
||||
# version = page.versions.latest
|
||||
# version.previous # go back one version
|
||||
# version.next # go forward one version
|
||||
#
|
||||
# See ActiveRecord::Acts::Versioned::ClassMethods#acts_as_versioned for configuration options
|
||||
module Versioned
|
||||
CALLBACKS = [:set_new_version, :save_version_on_create, :save_version?, :clear_changed_attributes]
|
||||
CALLBACKS = [:set_new_version, :save_version_on_create, :save_version?, :clear_altered_attributes]
|
||||
def self.included(base) # :nodoc:
|
||||
base.extend ClassMethods
|
||||
end
|
||||
@@ -80,7 +95,7 @@ module ActiveRecord #:nodoc:
|
||||
# end
|
||||
#
|
||||
# * <tt>if_changed</tt> - Simple way of specifying attributes that are required to be changed before saving a model. This takes
|
||||
# either a symbol or array of symbols. WARNING - This will attempt to overwrite any attribute setters you may have.
|
||||
# either a symbol or array of symbols. WARNING - This will attempt to overwrite any attribute setters you may have.
|
||||
# Use this instead if you want to write your own attribute setters (and ignore if_changed):
|
||||
#
|
||||
# def name=(new_name)
|
||||
@@ -133,7 +148,7 @@ module ActiveRecord #:nodoc:
|
||||
# # that create_table does
|
||||
# Post.create_versioned_table
|
||||
# end
|
||||
#
|
||||
#
|
||||
# def self.down
|
||||
# Post.drop_versioned_table
|
||||
# end
|
||||
@@ -157,11 +172,11 @@ module ActiveRecord #:nodoc:
|
||||
return if self.included_modules.include?(ActiveRecord::Acts::Versioned::ActMethods)
|
||||
|
||||
send :include, ActiveRecord::Acts::Versioned::ActMethods
|
||||
|
||||
|
||||
cattr_accessor :versioned_class_name, :versioned_foreign_key, :versioned_table_name, :versioned_inheritance_column,
|
||||
:version_column, :max_version_limit, :track_changed_attributes, :version_condition, :version_sequence_name, :non_versioned_columns,
|
||||
:version_column, :max_version_limit, :track_altered_attributes, :version_condition, :version_sequence_name, :non_versioned_columns,
|
||||
:version_association_options
|
||||
|
||||
|
||||
# legacy
|
||||
alias_method :non_versioned_fields, :non_versioned_columns
|
||||
alias_method :non_versioned_fields=, :non_versioned_columns=
|
||||
@@ -171,7 +186,7 @@ module ActiveRecord #:nodoc:
|
||||
alias_method :non_versioned_fields=, :non_versioned_columns=
|
||||
end
|
||||
|
||||
send :attr_accessor, :changed_attributes
|
||||
send :attr_accessor, :altered_attributes
|
||||
|
||||
self.versioned_class_name = options[:class_name] || "Version"
|
||||
self.versioned_foreign_key = options[:foreign_key] || self.to_s.foreign_key
|
||||
@@ -184,8 +199,7 @@ module ActiveRecord #:nodoc:
|
||||
self.non_versioned_columns = [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column]
|
||||
self.version_association_options = {
|
||||
:class_name => "#{self.to_s}::#{versioned_class_name}",
|
||||
:foreign_key => "#{versioned_foreign_key}",
|
||||
:order => 'version',
|
||||
:foreign_key => versioned_foreign_key,
|
||||
:dependent => :delete_all
|
||||
}.merge(options[:association_options] || {})
|
||||
|
||||
@@ -194,20 +208,30 @@ module ActiveRecord #:nodoc:
|
||||
silence_warnings do
|
||||
self.const_set(extension_module_name, Module.new(&extension))
|
||||
end
|
||||
|
||||
|
||||
options[:extend] = self.const_get(extension_module_name)
|
||||
end
|
||||
|
||||
class_eval do
|
||||
has_many :versions, version_association_options
|
||||
has_many :versions, version_association_options do
|
||||
# finds earliest version of this record
|
||||
def earliest
|
||||
@earliest ||= find(:first, :order => 'version')
|
||||
end
|
||||
|
||||
# find latest version of this record
|
||||
def latest
|
||||
@latest ||= find(:first, :order => 'version desc')
|
||||
end
|
||||
end
|
||||
before_save :set_new_version
|
||||
after_create :save_version_on_create
|
||||
after_update :save_version
|
||||
after_save :clear_old_versions
|
||||
after_save :clear_changed_attributes
|
||||
|
||||
after_save :clear_altered_attributes
|
||||
|
||||
unless options[:if_changed].nil?
|
||||
self.track_changed_attributes = true
|
||||
self.track_altered_attributes = true
|
||||
options[:if_changed] = [options[:if_changed]] unless options[:if_changed].is_a?(Array)
|
||||
options[:if_changed].each do |attr_name|
|
||||
define_method("#{attr_name}=") do |value|
|
||||
@@ -215,15 +239,40 @@ module ActiveRecord #:nodoc:
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
include options[:extend] if options[:extend].is_a?(Module)
|
||||
end
|
||||
|
||||
# create the dynamic versioned model
|
||||
const_set(versioned_class_name, Class.new(ActiveRecord::Base)).class_eval do
|
||||
def self.reloadable? ; false ; end
|
||||
# find first version before the given version
|
||||
def self.before(version)
|
||||
find :first, :order => 'version desc',
|
||||
:conditions => ["#{original_class.versioned_foreign_key} = ? and version < ?", version.send(original_class.versioned_foreign_key), version.version]
|
||||
end
|
||||
|
||||
# find first version after the given version.
|
||||
def self.after(version)
|
||||
find :first, :order => 'version',
|
||||
:conditions => ["#{original_class.versioned_foreign_key} = ? and version > ?", version.send(original_class.versioned_foreign_key), version.version]
|
||||
end
|
||||
|
||||
def previous
|
||||
self.class.before(self)
|
||||
end
|
||||
|
||||
def next
|
||||
self.class.after(self)
|
||||
end
|
||||
|
||||
def versions_count
|
||||
page.version
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
versioned_class.cattr_accessor :original_class
|
||||
versioned_class.original_class = self
|
||||
versioned_class.set_table_name versioned_table_name
|
||||
versioned_class.belongs_to self.to_s.demodulize.underscore.to_sym,
|
||||
:class_name => "::#{self.to_s}",
|
||||
@@ -232,17 +281,22 @@ module ActiveRecord #:nodoc:
|
||||
versioned_class.set_sequence_name version_sequence_name if version_sequence_name
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
module ActMethods
|
||||
def self.included(base) # :nodoc:
|
||||
base.extend ClassMethods
|
||||
end
|
||||
|
||||
|
||||
# Finds a specific version of this record
|
||||
def find_version(version = nil)
|
||||
self.class.find_version(id, version)
|
||||
end
|
||||
|
||||
# Saves a version of the model if applicable
|
||||
def save_version
|
||||
save_version_on_create if save_version?
|
||||
end
|
||||
|
||||
|
||||
# Saves a version of the model in the versioned table. This is called in the after_save callback by default
|
||||
def save_version_on_create
|
||||
rev = self.class.versioned_class.new
|
||||
@@ -263,16 +317,8 @@ module ActiveRecord #:nodoc:
|
||||
end
|
||||
end
|
||||
|
||||
# Finds a specific version of this model.
|
||||
def find_version(version)
|
||||
return version if version.is_a?(self.class.versioned_class)
|
||||
return nil if version.is_a?(ActiveRecord::Base)
|
||||
find_versions(:conditions => ['version = ?', version], :limit => 1).first
|
||||
end
|
||||
|
||||
# Finds versions of this model. Takes an options hash like <tt>find</tt>
|
||||
def find_versions(options = {})
|
||||
versions.find(:all, options)
|
||||
def versions_count
|
||||
version
|
||||
end
|
||||
|
||||
# Reverts a model to a given version. Takes either a version number or an instance of the versioned model
|
||||
@@ -280,14 +326,14 @@ module ActiveRecord #:nodoc:
|
||||
if version.is_a?(self.class.versioned_class)
|
||||
return false unless version.send(self.class.versioned_foreign_key) == self.id and !version.new_record?
|
||||
else
|
||||
return false unless version = find_version(version)
|
||||
return false unless version = versions.find_by_version(version)
|
||||
end
|
||||
self.clone_versioned_model(version, self)
|
||||
self.send("#{self.class.version_column}=", version.version)
|
||||
true
|
||||
end
|
||||
|
||||
# Reverts a model to a given version and saves the model.
|
||||
# Reverts a model to a given version and saves the model.
|
||||
# Takes either a version number or an instance of the versioned model
|
||||
def revert_to!(version)
|
||||
revert_to(version) ? save_without_revision : false
|
||||
@@ -313,36 +359,36 @@ module ActiveRecord #:nodoc:
|
||||
def versioned_attributes
|
||||
self.attributes.keys.select { |k| !self.class.non_versioned_columns.include?(k) }
|
||||
end
|
||||
|
||||
|
||||
# If called with no parameters, gets whether the current model has changed and needs to be versioned.
|
||||
# If called with a single parameter, gets whether the parameter has changed.
|
||||
def changed?(attr_name = nil)
|
||||
attr_name.nil? ?
|
||||
(!self.class.track_changed_attributes || (changed_attributes && changed_attributes.length > 0)) :
|
||||
(changed_attributes && changed_attributes.include?(attr_name.to_s))
|
||||
(!self.class.track_altered_attributes || (altered_attributes && altered_attributes.length > 0)) :
|
||||
(altered_attributes && altered_attributes.include?(attr_name.to_s))
|
||||
end
|
||||
|
||||
|
||||
# keep old dirty? method
|
||||
alias_method :dirty?, :changed?
|
||||
|
||||
|
||||
# Clones a model. Used when saving a new version or reverting a model's version.
|
||||
def clone_versioned_model(orig_model, new_model)
|
||||
self.versioned_attributes.each do |key|
|
||||
new_model.send("#{key}=", orig_model.attributes[key]) if orig_model.has_attribute?(key)
|
||||
new_model.send("#{key}=", orig_model.send(key)) if orig_model.has_attribute?(key)
|
||||
end
|
||||
|
||||
|
||||
if orig_model.is_a?(self.class.versioned_class)
|
||||
new_model[new_model.class.inheritance_column] = orig_model[self.class.versioned_inheritance_column]
|
||||
elsif new_model.is_a?(self.class.versioned_class)
|
||||
new_model[self.class.versioned_inheritance_column] = orig_model[orig_model.class.inheritance_column]
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Checks whether a new version shall be saved or not. Calls <tt>version_condition_met?</tt> and <tt>changed?</tt>.
|
||||
def save_version?
|
||||
version_condition_met? && changed?
|
||||
end
|
||||
|
||||
|
||||
# Checks condition set in the :if option to check whether a revision should be created or not. Override this for
|
||||
# custom version condition checking.
|
||||
def version_condition_met?
|
||||
@@ -353,7 +399,7 @@ module ActiveRecord #:nodoc:
|
||||
version_condition.call(self)
|
||||
else
|
||||
version_condition
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Executes the block with the versioning callbacks disabled.
|
||||
@@ -378,43 +424,45 @@ module ActiveRecord #:nodoc:
|
||||
|
||||
def empty_callback() end #:nodoc:
|
||||
|
||||
protected
|
||||
protected
|
||||
# sets the new version before saving, unless you're using optimistic locking. In that case, let it take care of the version.
|
||||
def set_new_version
|
||||
self.send("#{self.class.version_column}=", self.next_version) if new_record? || (!locking_enabled? && save_version?)
|
||||
end
|
||||
|
||||
|
||||
# Gets the next available version for the current record, or 1 for a new record
|
||||
def next_version
|
||||
return 1 if new_record?
|
||||
(versions.calculate(:max, :version) || 0) + 1
|
||||
end
|
||||
|
||||
|
||||
# clears current changed attributes. Called after save.
|
||||
def clear_changed_attributes
|
||||
self.changed_attributes = []
|
||||
def clear_altered_attributes
|
||||
self.altered_attributes = []
|
||||
end
|
||||
|
||||
def write_changed_attribute(attr_name, attr_value)
|
||||
# Convert to db type for comparison. Avoids failing Float<=>String comparisons.
|
||||
attr_value_for_db = self.class.columns_hash[attr_name.to_s].type_cast(attr_value)
|
||||
(self.changed_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db
|
||||
(self.altered_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db
|
||||
write_attribute(attr_name, attr_value_for_db)
|
||||
end
|
||||
|
||||
private
|
||||
CALLBACKS.each do |attr_name|
|
||||
alias_method "orig_#{attr_name}".to_sym, attr_name
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
# Finds a specific version of a specific row of this model
|
||||
def find_version(id, version)
|
||||
find_versions(id,
|
||||
:conditions => ["#{versioned_foreign_key} = ? AND version = ?", id, version],
|
||||
:limit => 1).first
|
||||
def find_version(id, version = nil)
|
||||
return find(id) unless version
|
||||
|
||||
conditions = ["#{versioned_foreign_key} = ? AND version = ?", id, version]
|
||||
options = { :conditions => conditions, :limit => 1 }
|
||||
|
||||
if result = find_versions(id, options).first
|
||||
result
|
||||
else
|
||||
raise RecordNotFound, "Couldn't find #{name} with ID=#{id} and VERSION=#{version}"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Finds versions of a specific model. Takes an options hash like <tt>find</tt>
|
||||
def find_versions(id, options = {})
|
||||
versioned_class.find :all, {
|
||||
@@ -426,7 +474,7 @@ module ActiveRecord #:nodoc:
|
||||
def versioned_columns
|
||||
self.columns.select { |c| !non_versioned_columns.include?(c.name) }
|
||||
end
|
||||
|
||||
|
||||
# Returns an instance of the dynamic versioned model
|
||||
def versioned_class
|
||||
const_get versioned_class_name
|
||||
@@ -438,36 +486,40 @@ module ActiveRecord #:nodoc:
|
||||
if !self.content_columns.find { |c| %w(version lock_version).include? c.name }
|
||||
self.connection.add_column table_name, :version, :integer
|
||||
end
|
||||
|
||||
|
||||
self.connection.create_table(versioned_table_name, create_table_options) do |t|
|
||||
t.column versioned_foreign_key, :integer
|
||||
t.column :version, :integer
|
||||
end
|
||||
|
||||
|
||||
updated_col = nil
|
||||
self.versioned_columns.each do |col|
|
||||
updated_col = col if !updated_col && %(updated_at updated_on).include?(col.name)
|
||||
self.connection.add_column versioned_table_name, col.name, col.type,
|
||||
:limit => col.limit,
|
||||
:default => col.default
|
||||
:default => col.default,
|
||||
:scale => col.scale,
|
||||
:precision => col.precision
|
||||
end
|
||||
|
||||
|
||||
if type_col = self.columns_hash[inheritance_column]
|
||||
self.connection.add_column versioned_table_name, versioned_inheritance_column, type_col.type,
|
||||
:limit => type_col.limit,
|
||||
:default => type_col.default
|
||||
:default => type_col.default,
|
||||
:scale => type_col.scale,
|
||||
:precision => type_col.precision
|
||||
end
|
||||
|
||||
|
||||
if updated_col.nil?
|
||||
self.connection.add_column versioned_table_name, :updated_at, :timestamp
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
# Rake migration task to drop the versioned table
|
||||
def drop_versioned_table
|
||||
self.connection.drop_table versioned_table_name
|
||||
end
|
||||
|
||||
|
||||
# Executes the block with the versioning callbacks disabled.
|
||||
#
|
||||
# Foo.without_revision do
|
||||
@@ -476,17 +528,18 @@ module ActiveRecord #:nodoc:
|
||||
#
|
||||
def without_revision(&block)
|
||||
class_eval do
|
||||
CALLBACKS.each do |attr_name|
|
||||
CALLBACKS.each do |attr_name|
|
||||
alias_method "orig_#{attr_name}".to_sym, attr_name
|
||||
alias_method attr_name, :empty_callback
|
||||
end
|
||||
end
|
||||
result = block.call
|
||||
block.call
|
||||
ensure
|
||||
class_eval do
|
||||
CALLBACKS.each do |attr_name|
|
||||
alias_method attr_name, "orig_#{attr_name}".to_sym
|
||||
end
|
||||
end
|
||||
result
|
||||
end
|
||||
|
||||
# Turns off optimistic locking for the duration of the block
|
||||
@@ -501,7 +554,7 @@ module ActiveRecord #:nodoc:
|
||||
result = block.call
|
||||
ActiveRecord::Base.lock_optimistically = true if current
|
||||
result
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+14
-13
@@ -1,12 +1,21 @@
|
||||
$:.unshift(File.dirname(__FILE__) + '/../../../rails/activesupport/lib')
|
||||
$:.unshift(File.dirname(__FILE__) + '/../../../rails/activerecord/lib')
|
||||
$:.unshift(File.dirname(__FILE__) + '/../lib')
|
||||
|
||||
require 'test/unit'
|
||||
require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb'))
|
||||
require 'active_record/fixtures'
|
||||
begin
|
||||
require 'active_support'
|
||||
require 'active_record'
|
||||
require 'active_record/fixtures'
|
||||
rescue LoadError
|
||||
require 'rubygems'
|
||||
retry
|
||||
end
|
||||
require 'acts_as_versioned'
|
||||
|
||||
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
|
||||
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
|
||||
ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite'])
|
||||
ActiveRecord::Base.configurations = {'test' => config[ENV['DB'] || 'sqlite3']}
|
||||
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
|
||||
|
||||
load(File.dirname(__FILE__) + "/schema.rb")
|
||||
|
||||
@@ -19,17 +28,9 @@ if ENV['DB'] == 'postgresql'
|
||||
end
|
||||
|
||||
Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/"
|
||||
$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path)
|
||||
$:.unshift(Test::Unit::TestCase.fixture_path)
|
||||
|
||||
class Test::Unit::TestCase #:nodoc:
|
||||
def create_fixtures(*table_names)
|
||||
if block_given?
|
||||
Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield }
|
||||
else
|
||||
Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names)
|
||||
end
|
||||
end
|
||||
|
||||
# Turn off transactional fixtures if you're working with MyISAM tables in MySQL
|
||||
self.use_transactional_fixtures = true
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
class Widget < ActiveRecord::Base
|
||||
acts_as_versioned :sequence_name => 'widgets_seq', :association_options => {
|
||||
:dependent => nil, :order => 'version desc'
|
||||
:dependent => :nullify, :order => 'version desc'
|
||||
}
|
||||
non_versioned_columns << 'foo'
|
||||
end
|
||||
@@ -9,9 +9,14 @@ if ActiveRecord::Base.connection.supports_migrations?
|
||||
class MigrationTest < Test::Unit::TestCase
|
||||
self.use_transactional_fixtures = false
|
||||
def teardown
|
||||
ActiveRecord::Base.connection.initialize_schema_information
|
||||
ActiveRecord::Base.connection.update "UPDATE schema_info SET version = 0"
|
||||
|
||||
if ActiveRecord::Base.connection.respond_to?(:initialize_schema_information)
|
||||
ActiveRecord::Base.connection.initialize_schema_information
|
||||
ActiveRecord::Base.connection.update "UPDATE schema_info SET version = 0"
|
||||
else
|
||||
ActiveRecord::Base.connection.initialize_schema_migrations_table
|
||||
ActiveRecord::Base.connection.assume_migrated_upto_version(0)
|
||||
end
|
||||
|
||||
Thing.connection.drop_table "things" rescue nil
|
||||
Thing.connection.drop_table "thing_versions" rescue nil
|
||||
Thing.reset_column_information
|
||||
@@ -21,8 +26,17 @@ if ActiveRecord::Base.connection.supports_migrations?
|
||||
assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' }
|
||||
# take 'er up
|
||||
ActiveRecord::Migrator.up(File.dirname(__FILE__) + '/fixtures/migrations/')
|
||||
t = Thing.create :title => 'blah blah'
|
||||
t = Thing.create :title => 'blah blah', :price => 123.45, :type => 'Thing'
|
||||
assert_equal 1, t.versions.size
|
||||
|
||||
# check that the price column has remembered its value correctly
|
||||
assert_equal t.price, t.versions.first.price
|
||||
assert_equal t.title, t.versions.first.title
|
||||
assert_equal t[:type], t.versions.first[:type]
|
||||
|
||||
# make sure that the precision of the price column has been preserved
|
||||
assert_equal 7, Thing::Version.columns.find{|c| c.name == "price"}.precision
|
||||
assert_equal 2, Thing::Version.columns.find{|c| c.name == "price"}.scale
|
||||
|
||||
# now lets take 'er back down
|
||||
ActiveRecord::Migrator.down(File.dirname(__FILE__) + '/fixtures/migrations/')
|
||||
|
||||
+103
-69
@@ -4,9 +4,10 @@ require File.join(File.dirname(__FILE__), 'fixtures/widget')
|
||||
|
||||
class VersionedTest < Test::Unit::TestCase
|
||||
fixtures :pages, :page_versions, :locked_pages, :locked_pages_revisions, :authors, :landmarks, :landmark_versions
|
||||
set_fixture_class :page_versions => Page::Version
|
||||
|
||||
def test_saves_versioned_copy
|
||||
p = Page.create :title => 'first title', :body => 'first body'
|
||||
p = Page.create! :title => 'first title', :body => 'first body'
|
||||
assert !p.new_record?
|
||||
assert_equal 1, p.versions.size
|
||||
assert_equal 1, p.version
|
||||
@@ -16,13 +17,13 @@ class VersionedTest < Test::Unit::TestCase
|
||||
def test_saves_without_revision
|
||||
p = pages(:welcome)
|
||||
old_versions = p.versions.count
|
||||
|
||||
|
||||
p.save_without_revision
|
||||
|
||||
|
||||
p.without_revision do
|
||||
p.update_attributes :title => 'changed'
|
||||
end
|
||||
|
||||
|
||||
assert_equal old_versions, p.versions.count
|
||||
end
|
||||
|
||||
@@ -30,7 +31,7 @@ class VersionedTest < Test::Unit::TestCase
|
||||
p = pages(:welcome)
|
||||
assert_equal 24, p.version
|
||||
assert_equal 'Welcome to the weblog', p.title
|
||||
|
||||
|
||||
assert p.revert_to!(p.versions.first.version), "Couldn't revert to 23"
|
||||
assert_equal 23, p.version
|
||||
assert_equal 'Welcome to the weblg', p.title
|
||||
@@ -57,56 +58,56 @@ class VersionedTest < Test::Unit::TestCase
|
||||
p = pages(:welcome)
|
||||
assert_equal 24, p.version
|
||||
assert_equal 'Welcome to the weblog', p.title
|
||||
|
||||
|
||||
assert p.revert_to!(p.versions.first), "Couldn't revert to 23"
|
||||
assert_equal 23, p.version
|
||||
assert_equal 'Welcome to the weblg', p.title
|
||||
end
|
||||
|
||||
|
||||
def test_rollback_fails_with_invalid_revision
|
||||
p = locked_pages(:welcome)
|
||||
assert !p.revert_to!(locked_pages(:thinking))
|
||||
end
|
||||
|
||||
def test_saves_versioned_copy_with_options
|
||||
p = LockedPage.create :title => 'first title'
|
||||
p = LockedPage.create! :title => 'first title'
|
||||
assert !p.new_record?
|
||||
assert_equal 1, p.versions.size
|
||||
assert_instance_of LockedPage.versioned_class, p.versions.first
|
||||
end
|
||||
|
||||
|
||||
def test_rollback_with_version_number_with_options
|
||||
p = locked_pages(:welcome)
|
||||
assert_equal 'Welcome to the weblog', p.title
|
||||
assert_equal 'LockedPage', p.versions.first.version_type
|
||||
|
||||
|
||||
assert p.revert_to!(p.versions.first.version), "Couldn't revert to 23"
|
||||
assert_equal 'Welcome to the weblg', p.title
|
||||
assert_equal 'LockedPage', p.versions.first.version_type
|
||||
end
|
||||
|
||||
|
||||
def test_rollback_with_version_class_with_options
|
||||
p = locked_pages(:welcome)
|
||||
assert_equal 'Welcome to the weblog', p.title
|
||||
assert_equal 'LockedPage', p.versions.first.version_type
|
||||
|
||||
|
||||
assert p.revert_to!(p.versions.first), "Couldn't revert to 1"
|
||||
assert_equal 'Welcome to the weblg', p.title
|
||||
assert_equal 'LockedPage', p.versions.first.version_type
|
||||
end
|
||||
|
||||
|
||||
def test_saves_versioned_copy_with_sti
|
||||
p = SpecialLockedPage.create :title => 'first title'
|
||||
p = SpecialLockedPage.create! :title => 'first title'
|
||||
assert !p.new_record?
|
||||
assert_equal 1, p.versions.size
|
||||
assert_instance_of LockedPage.versioned_class, p.versions.first
|
||||
assert_equal 'SpecialLockedPage', p.versions.first.version_type
|
||||
end
|
||||
|
||||
|
||||
def test_rollback_with_version_number_with_sti
|
||||
p = locked_pages(:thinking)
|
||||
assert_equal 'So I was thinking', p.title
|
||||
|
||||
|
||||
assert p.revert_to!(p.versions.first.version), "Couldn't revert to 1"
|
||||
assert_equal 'So I was thinking!!!', p.title
|
||||
assert_equal 'SpecialLockedPage', p.versions.first.version_type
|
||||
@@ -115,11 +116,11 @@ class VersionedTest < Test::Unit::TestCase
|
||||
def test_lock_version_works_with_versioning
|
||||
p = locked_pages(:thinking)
|
||||
p2 = LockedPage.find(p.id)
|
||||
|
||||
|
||||
p.title = 'fresh title'
|
||||
p.save
|
||||
assert_equal 2, p.versions.size # limit!
|
||||
|
||||
|
||||
assert_raises(ActiveRecord::StaleObjectError) do
|
||||
p2.title = 'stale title'
|
||||
p2.save
|
||||
@@ -127,15 +128,15 @@ class VersionedTest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_version_if_condition
|
||||
p = Page.create :title => "title"
|
||||
p = Page.create! :title => "title"
|
||||
assert_equal 1, p.version
|
||||
|
||||
|
||||
Page.feeling_good = false
|
||||
p.save
|
||||
assert_equal 1, p.version
|
||||
Page.feeling_good = true
|
||||
end
|
||||
|
||||
|
||||
def test_version_if_condition2
|
||||
# set new if condition
|
||||
Page.class_eval do
|
||||
@@ -143,46 +144,46 @@ class VersionedTest < Test::Unit::TestCase
|
||||
alias_method :old_feeling_good, :feeling_good?
|
||||
alias_method :feeling_good?, :new_feeling_good
|
||||
end
|
||||
|
||||
p = Page.create :title => "title"
|
||||
|
||||
p = Page.create! :title => "title"
|
||||
assert_equal 1, p.version # version does not increment
|
||||
assert_equal 1, p.versions(true).size
|
||||
|
||||
|
||||
p.update_attributes(:title => 'new title')
|
||||
assert_equal 1, p.version # version does not increment
|
||||
assert_equal 1, p.versions(true).size
|
||||
|
||||
|
||||
p.update_attributes(:title => 'a title')
|
||||
assert_equal 2, p.version
|
||||
assert_equal 2, p.versions(true).size
|
||||
|
||||
|
||||
# reset original if condition
|
||||
Page.class_eval { alias_method :feeling_good?, :old_feeling_good }
|
||||
end
|
||||
|
||||
|
||||
def test_version_if_condition_with_block
|
||||
# set new if condition
|
||||
old_condition = Page.version_condition
|
||||
Page.version_condition = Proc.new { |page| page.title[0..0] == 'b' }
|
||||
|
||||
p = Page.create :title => "title"
|
||||
|
||||
p = Page.create! :title => "title"
|
||||
assert_equal 1, p.version # version does not increment
|
||||
assert_equal 1, p.versions(true).size
|
||||
|
||||
|
||||
p.update_attributes(:title => 'a title')
|
||||
assert_equal 1, p.version # version does not increment
|
||||
assert_equal 1, p.versions(true).size
|
||||
|
||||
|
||||
p.update_attributes(:title => 'b title')
|
||||
assert_equal 2, p.version
|
||||
assert_equal 2, p.versions(true).size
|
||||
|
||||
|
||||
# reset original if condition
|
||||
Page.version_condition = old_condition
|
||||
end
|
||||
|
||||
def test_version_no_limit
|
||||
p = Page.create :title => "title", :body => 'first body'
|
||||
p = Page.create! :title => "title", :body => 'first body'
|
||||
p.save
|
||||
p.save
|
||||
5.times do |i|
|
||||
@@ -191,7 +192,7 @@ class VersionedTest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_version_max_limit
|
||||
p = LockedPage.create :title => "title"
|
||||
p = LockedPage.create! :title => "title"
|
||||
p.update_attributes(:title => "title1")
|
||||
p.update_attributes(:title => "title2")
|
||||
5.times do |i|
|
||||
@@ -199,31 +200,29 @@ class VersionedTest < Test::Unit::TestCase
|
||||
assert p.versions(true).size <= 2, "locked version can only store 2 versions"
|
||||
end
|
||||
end
|
||||
|
||||
def test_track_changed_attributes_default_value
|
||||
assert !Page.track_changed_attributes
|
||||
assert LockedPage.track_changed_attributes
|
||||
assert SpecialLockedPage.track_changed_attributes
|
||||
|
||||
def test_track_altered_attributes_default_value
|
||||
assert !Page.track_altered_attributes
|
||||
assert LockedPage.track_altered_attributes
|
||||
assert SpecialLockedPage.track_altered_attributes
|
||||
end
|
||||
|
||||
|
||||
def test_version_order
|
||||
assert_equal 23, pages(:welcome).versions.first.version
|
||||
assert_equal 24, pages(:welcome).versions.last.version
|
||||
assert_equal 23, pages(:welcome).find_versions.first.version
|
||||
assert_equal 24, pages(:welcome).find_versions.last.version
|
||||
end
|
||||
|
||||
def test_track_changed_attributes
|
||||
p = LockedPage.create :title => "title"
|
||||
|
||||
def test_track_altered_attributes
|
||||
p = LockedPage.create! :title => "title"
|
||||
assert_equal 1, p.lock_version
|
||||
assert_equal 1, p.versions(true).size
|
||||
|
||||
|
||||
p.title = 'title'
|
||||
assert !p.save_version?
|
||||
p.save
|
||||
assert_equal 2, p.lock_version # still increments version because of optimistic locking
|
||||
assert_equal 1, p.versions(true).size
|
||||
|
||||
|
||||
p.title = 'updated title'
|
||||
assert p.save_version?
|
||||
p.save
|
||||
@@ -236,27 +235,38 @@ class VersionedTest < Test::Unit::TestCase
|
||||
assert_equal 4, p.lock_version
|
||||
assert_equal 2, p.versions(true).size # version 1 deleted
|
||||
end
|
||||
|
||||
|
||||
def assert_page_title(p, i, version_field = :version)
|
||||
p.title = "title#{i}"
|
||||
p.save
|
||||
assert_equal "title#{i}", p.title
|
||||
assert_equal (i+4), p.send(version_field)
|
||||
end
|
||||
|
||||
|
||||
def test_find_versions
|
||||
assert_equal 2, locked_pages(:welcome).versions.size
|
||||
assert_equal 1, locked_pages(:welcome).find_versions(:conditions => ['title LIKE ?', '%weblog%']).length
|
||||
assert_equal 2, locked_pages(:welcome).find_versions(:conditions => ['title LIKE ?', '%web%']).length
|
||||
assert_equal 0, locked_pages(:thinking).find_versions(:conditions => ['title LIKE ?', '%web%']).length
|
||||
assert_equal 2, locked_pages(:welcome).find_versions.length
|
||||
assert_equal 1, locked_pages(:welcome).versions.find(:all, :conditions => ['title LIKE ?', '%weblog%']).length
|
||||
assert_equal 2, locked_pages(:welcome).versions.find(:all, :conditions => ['title LIKE ?', '%web%']).length
|
||||
assert_equal 0, locked_pages(:thinking).versions.find(:all, :conditions => ['title LIKE ?', '%web%']).length
|
||||
assert_equal 2, locked_pages(:welcome).versions.length
|
||||
end
|
||||
|
||||
|
||||
def test_find_version
|
||||
assert_equal page_versions(:welcome_1), Page.find_version(pages(:welcome).id, 23)
|
||||
assert_equal page_versions(:welcome_2), Page.find_version(pages(:welcome).id, 24)
|
||||
assert_equal pages(:welcome), Page.find_version(pages(:welcome).id)
|
||||
|
||||
assert_equal page_versions(:welcome_1), pages(:welcome).find_version(23)
|
||||
assert_equal page_versions(:welcome_2), pages(:welcome).find_version(24)
|
||||
assert_equal pages(:welcome), pages(:welcome).find_version
|
||||
|
||||
assert_raise(ActiveRecord::RecordNotFound) { Page.find_version(pages(:welcome).id, 1) }
|
||||
assert_raise(ActiveRecord::RecordNotFound) { Page.find_version(0, 23) }
|
||||
end
|
||||
|
||||
def test_with_sequence
|
||||
assert_equal 'widgets_seq', Widget.versioned_class.sequence_name
|
||||
Widget.create :name => 'new widget'
|
||||
Widget.create :name => 'new widget'
|
||||
Widget.create :name => 'new widget'
|
||||
3.times { Widget.create! :name => 'new widget' }
|
||||
assert_equal 3, Widget.count
|
||||
assert_equal 3, Widget.versioned_class.count
|
||||
end
|
||||
@@ -268,26 +278,26 @@ class VersionedTest < Test::Unit::TestCase
|
||||
def test_has_many_through_with_custom_association
|
||||
assert_equal [authors(:caged), authors(:mly)], pages(:welcome).revisors
|
||||
end
|
||||
|
||||
|
||||
def test_referential_integrity
|
||||
pages(:welcome).destroy
|
||||
assert_equal 0, Page.count
|
||||
assert_equal 0, Page::Version.count
|
||||
end
|
||||
|
||||
|
||||
def test_association_options
|
||||
association = Page.reflect_on_association(:versions)
|
||||
options = association.options
|
||||
assert_equal :delete_all, options[:dependent]
|
||||
assert_equal 'version', options[:order]
|
||||
|
||||
|
||||
association = Widget.reflect_on_association(:versions)
|
||||
options = association.options
|
||||
assert_nil options[:dependent]
|
||||
assert_equal :nullify, options[:dependent]
|
||||
assert_equal 'version desc', options[:order]
|
||||
assert_equal 'widget_id', options[:foreign_key]
|
||||
|
||||
widget = Widget.create :name => 'new widget'
|
||||
|
||||
widget = Widget.create! :name => 'new widget'
|
||||
assert_equal 1, Widget.count
|
||||
assert_equal 1, Widget.versioned_class.count
|
||||
widget.destroy
|
||||
@@ -300,14 +310,38 @@ class VersionedTest < Test::Unit::TestCase
|
||||
page_version = page.versions.last
|
||||
assert_equal page, page_version.page
|
||||
end
|
||||
|
||||
def test_unchanged_attributes
|
||||
landmarks(:washington).attributes = landmarks(:washington).attributes
|
||||
|
||||
def test_unaltered_attributes
|
||||
landmarks(:washington).attributes = landmarks(:washington).attributes.except("id")
|
||||
assert !landmarks(:washington).changed?
|
||||
end
|
||||
|
||||
|
||||
def test_unchanged_string_attributes
|
||||
landmarks(:washington).attributes = landmarks(:washington).attributes.inject({}) { |params, (key, value)| params.update key => value.to_s }
|
||||
landmarks(:washington).attributes = landmarks(:washington).attributes.except("id").inject({}) { |params, (key, value)| params.update(key => value.to_s) }
|
||||
assert !landmarks(:washington).changed?
|
||||
end
|
||||
end
|
||||
|
||||
def test_should_find_earliest_version
|
||||
assert_equal page_versions(:welcome_1), pages(:welcome).versions.earliest
|
||||
end
|
||||
|
||||
def test_should_find_latest_version
|
||||
assert_equal page_versions(:welcome_2), pages(:welcome).versions.latest
|
||||
end
|
||||
|
||||
def test_should_find_previous_version
|
||||
assert_equal page_versions(:welcome_1), page_versions(:welcome_2).previous
|
||||
assert_equal page_versions(:welcome_1), pages(:welcome).versions.before(page_versions(:welcome_2))
|
||||
end
|
||||
|
||||
def test_should_find_next_version
|
||||
assert_equal page_versions(:welcome_2), page_versions(:welcome_1).next
|
||||
assert_equal page_versions(:welcome_2), pages(:welcome).versions.after(page_versions(:welcome_1))
|
||||
end
|
||||
|
||||
def test_should_find_version_count
|
||||
assert_equal 24, pages(:welcome).versions_count
|
||||
assert_equal 24, page_versions(:welcome_1).versions_count
|
||||
assert_equal 24, page_versions(:welcome_2).versions_count
|
||||
end
|
||||
end
|
||||
@@ -13,6 +13,7 @@ module Redmine
|
||||
|
||||
class_eval do
|
||||
has_many :watchers, :as => :watchable, :dependent => :delete_all
|
||||
has_many :watcher_users, :through => :watchers, :source => :user
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -22,25 +23,40 @@ module Redmine
|
||||
base.extend ClassMethods
|
||||
end
|
||||
|
||||
# Returns an array of users that are proposed as watchers
|
||||
def addable_watcher_users
|
||||
self.project.users.sort - self.watcher_users
|
||||
end
|
||||
|
||||
# Adds user as a watcher
|
||||
def add_watcher(user)
|
||||
self.watchers << Watcher.new(:user => user)
|
||||
end
|
||||
|
||||
# Removes user from the watchers list
|
||||
def remove_watcher(user)
|
||||
return nil unless user && user.is_a?(User)
|
||||
Watcher.delete_all "watchable_type = '#{self.class}' AND watchable_id = #{self.id} AND user_id = #{user.id}"
|
||||
end
|
||||
|
||||
# Adds/removes watcher
|
||||
def set_watcher(user, watching=true)
|
||||
watching ? add_watcher(user) : remove_watcher(user)
|
||||
end
|
||||
|
||||
# Returns if object is watched by user
|
||||
def watched_by?(user)
|
||||
!self.watchers.find(:first,
|
||||
:conditions => ["#{Watcher.table_name}.user_id = ?", user.id]).nil?
|
||||
end
|
||||
|
||||
# Returns an array of watchers' email addresses
|
||||
def watcher_recipients
|
||||
self.watchers.collect { |w| w.user.mail if w.user.active? }.compact
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
# Returns the objects that are watched by user
|
||||
def watched_by(user)
|
||||
find(:all,
|
||||
:include => :watchers,
|
||||
@@ -50,4 +66,4 @@ module Redmine
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -122,7 +122,7 @@ module Scanners
|
||||
end
|
||||
|
||||
when :include_expected
|
||||
if scan(/<[^>\n]+>?|"[^"\n\\]*(?:\\.[^"\n\\]*)*"?/)
|
||||
if scan(/[^\n]+/)
|
||||
kind = :include
|
||||
state = :initial
|
||||
|
||||
|
||||
+2
-2
@@ -138,8 +138,8 @@ module ActionView #:nodoc:
|
||||
def add_options(option_tags, options, value = nil)
|
||||
option_tags = "<option value=\"\"></option>\n" + option_tags if options[:include_blank]
|
||||
|
||||
if value.blank? && options[:prompt]
|
||||
("<option value=\"\">#{options[:prompt].kind_of?(String) ? options[:prompt] : l(:actionview_instancetag_blank_option)}</option>\n") + option_tags
|
||||
if options[:prompt]
|
||||
("<option value=\"\">--- #{options[:prompt].kind_of?(String) ? options[:prompt] : l(:actionview_instancetag_blank_option)} ---</option>\n") + option_tags
|
||||
else
|
||||
option_tags
|
||||
end
|
||||
|
||||
+1
-1
@@ -168,7 +168,7 @@ module ActiveRecord #:nodoc:
|
||||
if attr == "base"
|
||||
full_messages << (msg.is_a?(Symbol) ? l(msg) : msg)
|
||||
else
|
||||
full_messages << @base.class.human_attribute_name(attr) + " " + (msg.is_a?(Symbol) ? l(msg) : msg)
|
||||
full_messages << @base.class.human_attribute_name(attr) + " " + (msg.is_a?(Symbol) ? l(msg) : msg.to_s)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Vendored
+7
-1
@@ -1,3 +1,9 @@
|
||||
require 'rfpdf'
|
||||
|
||||
ActionView::Base::register_template_handler 'rfpdf', RFPDF::View
|
||||
begin
|
||||
ActionView::Template::register_template_handler 'rfpdf', RFPDF::View
|
||||
rescue NameError
|
||||
# Rails < 2.1
|
||||
RFPDF::View.backward_compatibility_mode = true
|
||||
ActionView::Base::register_template_handler 'rfpdf', RFPDF::View
|
||||
end
|
||||
|
||||
+473
-473
@@ -1,473 +1,473 @@
|
||||
# Copyright (c) 2006 4ssoM LLC <www.4ssoM.com>
|
||||
# 1.12 contributed by Ed Moss.
|
||||
#
|
||||
# The MIT License
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
#
|
||||
# This is direct port of chinese.php
|
||||
#
|
||||
# Chinese PDF support.
|
||||
#
|
||||
# Usage is as follows:
|
||||
#
|
||||
# require 'fpdf'
|
||||
# require 'chinese'
|
||||
# pdf = FPDF.new
|
||||
# pdf.extend(PDF_Chinese)
|
||||
#
|
||||
# This allows it to be combined with other extensions, such as the bookmark
|
||||
# module.
|
||||
|
||||
module PDF_Chinese
|
||||
|
||||
Big5_widths={' '=>250,'!'=>250,'"'=>408,'#'=>668,''=>490,'%'=>875,'&'=>698,'\''=>250,
|
||||
'('=>240,')'=>240,'*'=>417,'+'=>667,','=>250,'-'=>313,'.'=>250,'/'=>520,'0'=>500,'1'=>500,
|
||||
'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>250,''=>250,
|
||||
'<'=>667,'='=>667,'>'=>667,'?'=>396,'@'=>921,'A'=>677,'B'=>615,'C'=>719,'D'=>760,'E'=>625,
|
||||
'F'=>552,'G'=>771,'H'=>802,'I'=>354,'J'=>354,'K'=>781,'L'=>604,'M'=>927,'N'=>750,'O'=>823,
|
||||
'P'=>563,'Q'=>823,'R'=>729,'S'=>542,'T'=>698,'U'=>771,'V'=>729,'W'=>948,'X'=>771,'Y'=>677,
|
||||
'Z'=>635,'['=>344,'\\'=>520,']'=>344,'^'=>469,'_'=>500,'`'=>250,'a'=>469,'b'=>521,'c'=>427,
|
||||
'd'=>521,'e'=>438,'f'=>271,'g'=>469,'h'=>531,'i'=>250,'j'=>250,'k'=>458,'l'=>240,'m'=>802,
|
||||
'n'=>531,'o'=>500,'p'=>521,'q'=>521,'r'=>365,'s'=>333,'t'=>292,'u'=>521,'v'=>458,'w'=>677,
|
||||
'x'=>479,'y'=>458,'z'=>427,'{'=>480,'|'=>496,'end'=>480,'~'=>667}
|
||||
|
||||
GB_widths={' '=>207,'!'=>270,'"'=>342,'#'=>467,''=>462,'%'=>797,'&'=>710,'\''=>239,
|
||||
'('=>374,')'=>374,'*'=>423,'+'=>605,','=>238,'-'=>375,'.'=>238,'/'=>334,'0'=>462,'1'=>462,
|
||||
'2'=>462,'3'=>462,'4'=>462,'5'=>462,'6'=>462,'7'=>462,'8'=>462,'9'=>462,':'=>238,''=>238,
|
||||
'<'=>605,'='=>605,'>'=>605,'?'=>344,'@'=>748,'A'=>684,'B'=>560,'C'=>695,'D'=>739,'E'=>563,
|
||||
'F'=>511,'G'=>729,'H'=>793,'I'=>318,'J'=>312,'K'=>666,'L'=>526,'M'=>896,'N'=>758,'O'=>772,
|
||||
'P'=>544,'Q'=>772,'R'=>628,'S'=>465,'T'=>607,'U'=>753,'V'=>711,'W'=>972,'X'=>647,'Y'=>620,
|
||||
'Z'=>607,'['=>374,'\\'=>333,']'=>374,'^'=>606,'_'=>500,'`'=>239,'a'=>417,'b'=>503,'c'=>427,
|
||||
'd'=>529,'e'=>415,'f'=>264,'g'=>444,'h'=>518,'i'=>241,'j'=>230,'k'=>495,'l'=>228,'m'=>793,
|
||||
'n'=>527,'o'=>524,'p'=>524,'q'=>504,'r'=>338,'s'=>336,'t'=>277,'u'=>517,'v'=>450,'w'=>652,
|
||||
'x'=>466,'y'=>452,'z'=>407,'{'=>370,'|'=>258,'end'=>370,'~'=>605}
|
||||
|
||||
def AddCIDFont(family,style,name,cw,cMap,registry)
|
||||
#ActionController::Base::logger.debug registry.to_a.join(":").to_s
|
||||
fontkey=family.downcase+style.upcase
|
||||
unless @fonts[fontkey].nil?
|
||||
Error("Font already added: family style")
|
||||
end
|
||||
i=@fonts.length+1
|
||||
name=name.gsub(' ','')
|
||||
@fonts[fontkey]={'i'=>i,'type'=>'Type0','name'=>name,'up'=>-130,'ut'=>40,'cw'=>cw, 'CMap'=>cMap,'registry'=>registry}
|
||||
end
|
||||
|
||||
def AddCIDFonts(family,name,cw,cMap,registry)
|
||||
AddCIDFont(family,'',name,cw,cMap,registry)
|
||||
AddCIDFont(family,'B',name+',Bold',cw,cMap,registry)
|
||||
AddCIDFont(family,'I',name+',Italic',cw,cMap,registry)
|
||||
AddCIDFont(family,'BI',name+',BoldItalic',cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddBig5Font(family='Big5',name='MSungStd-Light-Acro')
|
||||
#Add Big5 font with proportional Latin
|
||||
cw=Big5_widths
|
||||
cMap='ETenms-B5-H'
|
||||
registry={'ordering'=>'CNS1','supplement'=>0}
|
||||
#ActionController::Base::logger.debug registry.to_a.join(":").to_s
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddBig5hwFont(family='Big5-hw',name='MSungStd-Light-Acro')
|
||||
#Add Big5 font with half-witdh Latin
|
||||
cw = {}
|
||||
32.upto(126) do |i|
|
||||
cw[i.chr]=500
|
||||
end
|
||||
cMap='ETen-B5-H'
|
||||
registry={'ordering'=>'CNS1','supplement'=>0}
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddGBFont(family='GB',name='STSongStd-Light-Acro')
|
||||
#Add GB font with proportional Latin
|
||||
cw=GB_widths
|
||||
cMap='GBKp-EUC-H'
|
||||
registry={'ordering'=>'GB1','supplement'=>2}
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddGBhwFont(family='GB-hw',name='STSongStd-Light-Acro')
|
||||
#Add GB font with half-width Latin
|
||||
32.upto(126) do |i|
|
||||
cw[i.chr]=500
|
||||
end
|
||||
cMap='GBK-EUC-H'
|
||||
registry={'ordering'=>'GB1','supplement'=>2}
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def GetStringWidth(s)
|
||||
if(@CurrentFont['type']=='Type0')
|
||||
return GetMBStringWidth(s)
|
||||
else
|
||||
return super(s)
|
||||
end
|
||||
end
|
||||
|
||||
def GetMBStringWidth(s)
|
||||
#Multi-byte version of GetStringWidth()
|
||||
l=0
|
||||
cw=@CurrentFont['cw']
|
||||
nb=s.length
|
||||
i=0
|
||||
while(i<nb)
|
||||
c=s[i]
|
||||
if(c<128)
|
||||
l+=cw[c.chr] if cw[c.chr]
|
||||
i+=1
|
||||
else
|
||||
l+=1000
|
||||
i+=2
|
||||
end
|
||||
end
|
||||
return l*@FontSize/1000
|
||||
end
|
||||
|
||||
def MultiCell(w,h,txt,border=0,align='L',fill=0)
|
||||
if(@CurrentFont['type']=='Type0')
|
||||
MBMultiCell(w,h,txt,border,align,fill)
|
||||
else
|
||||
super(w,h,txt,border,align,fill)
|
||||
end
|
||||
end
|
||||
|
||||
def MBMultiCell(w,h,txt,border=0,align='L',fill=0)
|
||||
#Multi-byte version of MultiCell()
|
||||
cw=@CurrentFont['cw']
|
||||
if(w==0)
|
||||
w=@w-@rMargin-@x
|
||||
end
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
s=txt.gsub("\r",'')
|
||||
nb=s.length
|
||||
if(nb>0 and s[nb-1]=="\n")
|
||||
nb-=1
|
||||
end
|
||||
b=0
|
||||
if(border)
|
||||
if(border==1)
|
||||
border='LTRB'
|
||||
b='LRT'
|
||||
b2='LR'
|
||||
else
|
||||
b2=''
|
||||
if(border.to_s.index('L'))
|
||||
b2+='L'
|
||||
end
|
||||
if(border.to_s.index('R'))
|
||||
b2+='R'
|
||||
end
|
||||
b=border.to_s.index('T') ? b2+'T' : b2
|
||||
end
|
||||
end
|
||||
sep=-1
|
||||
i=0
|
||||
j=0
|
||||
l=0
|
||||
nl=1
|
||||
while(i<nb)
|
||||
#Get next character
|
||||
c=s[i]
|
||||
#Check if ASCII or MB
|
||||
ascii=(c<128)
|
||||
if(c=="\n")
|
||||
#Explicit line break
|
||||
Cell(w,h,s[j,i-j],b,2,align,fill)
|
||||
i+=1
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
nl+=1
|
||||
if(border and nl==2)
|
||||
b=b2
|
||||
end
|
||||
next
|
||||
end
|
||||
if(!ascii)
|
||||
sep=i
|
||||
ls=l
|
||||
elsif(c==' ')
|
||||
sep=i
|
||||
ls=l
|
||||
end
|
||||
l+=ascii ? (cw[c.chr] || 0) : 1000
|
||||
if(l>wmax)
|
||||
#Automatic line break
|
||||
if(sep==-1 or i==j)
|
||||
if(i==j)
|
||||
i+=ascii ? 1 : 2
|
||||
end
|
||||
Cell(w,h,s[j,i-j],b,2,align,fill)
|
||||
else
|
||||
Cell(w,h,s[j,sep-j],b,2,align,fill)
|
||||
i=(s[sep]==' ') ? sep+1 : sep
|
||||
end
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
# nl+=1
|
||||
if(border and nl==2)
|
||||
b=b2
|
||||
end
|
||||
else
|
||||
i+=ascii ? 1 : 2
|
||||
end
|
||||
end
|
||||
#Last chunk
|
||||
if(border and not border.to_s.index('B').nil?)
|
||||
b+='B'
|
||||
end
|
||||
Cell(w,h,s[j,i-j],b,2,align,fill)
|
||||
@x=@lMargin
|
||||
end
|
||||
|
||||
def Write(h,txt,link='')
|
||||
if(@CurrentFont['type']=='Type0')
|
||||
MBWrite(h,txt,link)
|
||||
else
|
||||
super(h,txt,link)
|
||||
end
|
||||
end
|
||||
|
||||
def MBWrite(h,txt,link)
|
||||
#Multi-byte version of Write()
|
||||
cw=@CurrentFont['cw']
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
s=txt.gsub("\r",'')
|
||||
nb=s.length
|
||||
sep=-1
|
||||
i=0
|
||||
j=0
|
||||
l=0
|
||||
nl=1
|
||||
while(i<nb)
|
||||
#Get next character
|
||||
c=s[i]
|
||||
#Check if ASCII or MB
|
||||
ascii=(c<128)
|
||||
if(c=="\n")
|
||||
#Explicit line break
|
||||
Cell(w,h,s[j,i-j],0,2,'',0,link)
|
||||
i+=1
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
if(nl==1)
|
||||
@x=@lMargin
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
end
|
||||
nl+=1
|
||||
next
|
||||
end
|
||||
if(!ascii or c==' ')
|
||||
sep=i
|
||||
end
|
||||
l+=ascii ? cw[c.chr] : 1000
|
||||
if(l>wmax)
|
||||
#Automatic line break
|
||||
if(sep==-1 or i==j)
|
||||
if(@x>@lMargin)
|
||||
#Move to next line
|
||||
@x=@lMargin
|
||||
@y+=h
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
i+=1
|
||||
nl+=1
|
||||
next
|
||||
end
|
||||
if(i==j)
|
||||
i+=ascii ? 1 : 2
|
||||
end
|
||||
Cell(w,h,s[j,i-j],0,2,'',0,link)
|
||||
else
|
||||
Cell(w,h,s[j,sep-j],0,2,'',0,link)
|
||||
i=(s[sep]==' ') ? sep+1 : sep
|
||||
end
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
if(nl==1)
|
||||
@x=@lMargin
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
end
|
||||
nl+=1
|
||||
else
|
||||
i+=ascii ? 1 : 2
|
||||
end
|
||||
end
|
||||
#Last chunk
|
||||
if(i!=j)
|
||||
Cell(l/1000*@FontSize,h,s[j,i-j],0,0,'',0,link)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def putfonts()
|
||||
nf=@n
|
||||
@diffs.each do |diff|
|
||||
#Encodings
|
||||
newobj()
|
||||
out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['+diff+']>>')
|
||||
out('endobj')
|
||||
end
|
||||
# mqr=get_magic_quotes_runtime()
|
||||
# set_magic_quotes_runtime(0)
|
||||
@FontFiles.each_pair do |file, info|
|
||||
#Font file embedding
|
||||
newobj()
|
||||
@FontFiles[file]['n']=@n
|
||||
if(defined('FPDF_FONTPATH'))
|
||||
file=FPDF_FONTPATH+file
|
||||
end
|
||||
size=filesize(file)
|
||||
if(!size)
|
||||
Error('Font file not found')
|
||||
end
|
||||
out('<</Length '+size)
|
||||
if(file[-2]=='.z')
|
||||
out('/Filter /FlateDecode')
|
||||
end
|
||||
out('/Length1 '+info['length1'])
|
||||
unless info['length2'].nil?
|
||||
out('/Length2 '+info['length2']+' /Length3 0')
|
||||
end
|
||||
out('>>')
|
||||
f=fopen(file,'rb')
|
||||
putstream(fread(f,size))
|
||||
fclose(f)
|
||||
out('endobj')
|
||||
end
|
||||
#
|
||||
# set_magic_quotes_runtime(mqr)
|
||||
#
|
||||
@fonts.each_pair do |k, font|
|
||||
#Font objects
|
||||
newobj()
|
||||
@fonts[k]['n']=@n
|
||||
out('<</Type /Font')
|
||||
if(font['type']=='Type0')
|
||||
putType0(font)
|
||||
else
|
||||
name=font['name']
|
||||
out('/BaseFont /'+name)
|
||||
if(font['type']=='core')
|
||||
#Standard font
|
||||
out('/Subtype /Type1')
|
||||
if(name!='Symbol' and name!='ZapfDingbats')
|
||||
out('/Encoding /WinAnsiEncoding')
|
||||
end
|
||||
else
|
||||
#Additional font
|
||||
out('/Subtype /'+font['type'])
|
||||
out('/FirstChar 32')
|
||||
out('/LastChar 255')
|
||||
out('/Widths '+(@n+1)+' 0 R')
|
||||
out('/FontDescriptor '+(@n+2)+' 0 R')
|
||||
if(font['enc'])
|
||||
if !font['diff'].nil?
|
||||
out('/Encoding '+(nf+font['diff'])+' 0 R')
|
||||
else
|
||||
out('/Encoding /WinAnsiEncoding')
|
||||
end
|
||||
end
|
||||
end
|
||||
out('>>')
|
||||
out('endobj')
|
||||
if(font['type']!='core')
|
||||
#Widths
|
||||
newobj()
|
||||
cw=font['cw']
|
||||
s='['
|
||||
32.upto(255) do |i|
|
||||
s+=cw[i.chr]+' '
|
||||
end
|
||||
out(s+']')
|
||||
out('endobj')
|
||||
#Descriptor
|
||||
newobj()
|
||||
s='<</Type /FontDescriptor /FontName /'+name
|
||||
font['desc'].each_pair do |k, v|
|
||||
s+=' /'+k+' '+v
|
||||
end
|
||||
file=font['file']
|
||||
if(file)
|
||||
s+=' /FontFile'+(font['type']=='Type1' ? '' : '2')+' '+@FontFiles[file]['n']+' 0 R'
|
||||
end
|
||||
out(s+'>>')
|
||||
out('endobj')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def putType0(font)
|
||||
#Type0
|
||||
out('/Subtype /Type0')
|
||||
out('/BaseFont /'+font['name']+'-'+font['CMap'])
|
||||
out('/Encoding /'+font['CMap'])
|
||||
out('/DescendantFonts ['+(@n+1).to_s+' 0 R]')
|
||||
out('>>')
|
||||
out('endobj')
|
||||
#CIDFont
|
||||
newobj()
|
||||
out('<</Type /Font')
|
||||
out('/Subtype /CIDFontType0')
|
||||
out('/BaseFont /'+font['name'])
|
||||
out('/CIDSystemInfo <</Registry '+textstring('Adobe')+' /Ordering '+textstring(font['registry']['ordering'])+' /Supplement '+font['registry']['supplement'].to_s+'>>')
|
||||
out('/FontDescriptor '+(@n+1).to_s+' 0 R')
|
||||
if(font['CMap']=='ETen-B5-H')
|
||||
w='13648 13742 500'
|
||||
elsif(font['CMap']=='GBK-EUC-H')
|
||||
w='814 907 500 7716 [500]'
|
||||
else
|
||||
# ActionController::Base::logger.debug font['cw'].keys.sort.join(' ').to_s
|
||||
# ActionController::Base::logger.debug font['cw'].values.join(' ').to_s
|
||||
w='1 ['
|
||||
font['cw'].keys.sort.each {|key|
|
||||
w+=font['cw'][key].to_s + " "
|
||||
# ActionController::Base::logger.debug key.to_s
|
||||
# ActionController::Base::logger.debug font['cw'][key].to_s
|
||||
}
|
||||
w +=']'
|
||||
end
|
||||
out('/W ['+w+']>>')
|
||||
out('endobj')
|
||||
#Font descriptor
|
||||
newobj()
|
||||
out('<</Type /FontDescriptor')
|
||||
out('/FontName /'+font['name'])
|
||||
out('/Flags 6')
|
||||
out('/FontBBox [0 -200 1000 900]')
|
||||
out('/ItalicAngle 0')
|
||||
out('/Ascent 800')
|
||||
out('/Descent -200')
|
||||
out('/CapHeight 800')
|
||||
out('/StemV 50')
|
||||
out('>>')
|
||||
out('endobj')
|
||||
end
|
||||
end
|
||||
# Copyright (c) 2006 4ssoM LLC <www.4ssoM.com>
|
||||
# 1.12 contributed by Ed Moss.
|
||||
#
|
||||
# The MIT License
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
#
|
||||
# This is direct port of chinese.php
|
||||
#
|
||||
# Chinese PDF support.
|
||||
#
|
||||
# Usage is as follows:
|
||||
#
|
||||
# require 'fpdf'
|
||||
# require 'chinese'
|
||||
# pdf = FPDF.new
|
||||
# pdf.extend(PDF_Chinese)
|
||||
#
|
||||
# This allows it to be combined with other extensions, such as the bookmark
|
||||
# module.
|
||||
|
||||
module PDF_Chinese
|
||||
|
||||
Big5_widths={' '=>250,'!'=>250,'"'=>408,'#'=>668,''=>490,'%'=>875,'&'=>698,'\''=>250,
|
||||
'('=>240,')'=>240,'*'=>417,'+'=>667,','=>250,'-'=>313,'.'=>250,'/'=>520,'0'=>500,'1'=>500,
|
||||
'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>250,''=>250,
|
||||
'<'=>667,'='=>667,'>'=>667,'?'=>396,'@'=>921,'A'=>677,'B'=>615,'C'=>719,'D'=>760,'E'=>625,
|
||||
'F'=>552,'G'=>771,'H'=>802,'I'=>354,'J'=>354,'K'=>781,'L'=>604,'M'=>927,'N'=>750,'O'=>823,
|
||||
'P'=>563,'Q'=>823,'R'=>729,'S'=>542,'T'=>698,'U'=>771,'V'=>729,'W'=>948,'X'=>771,'Y'=>677,
|
||||
'Z'=>635,'['=>344,'\\'=>520,']'=>344,'^'=>469,'_'=>500,'`'=>250,'a'=>469,'b'=>521,'c'=>427,
|
||||
'd'=>521,'e'=>438,'f'=>271,'g'=>469,'h'=>531,'i'=>250,'j'=>250,'k'=>458,'l'=>240,'m'=>802,
|
||||
'n'=>531,'o'=>500,'p'=>521,'q'=>521,'r'=>365,'s'=>333,'t'=>292,'u'=>521,'v'=>458,'w'=>677,
|
||||
'x'=>479,'y'=>458,'z'=>427,'{'=>480,'|'=>496,'end'=>480,'~'=>667}
|
||||
|
||||
GB_widths={' '=>207,'!'=>270,'"'=>342,'#'=>467,''=>462,'%'=>797,'&'=>710,'\''=>239,
|
||||
'('=>374,')'=>374,'*'=>423,'+'=>605,','=>238,'-'=>375,'.'=>238,'/'=>334,'0'=>462,'1'=>462,
|
||||
'2'=>462,'3'=>462,'4'=>462,'5'=>462,'6'=>462,'7'=>462,'8'=>462,'9'=>462,':'=>238,''=>238,
|
||||
'<'=>605,'='=>605,'>'=>605,'?'=>344,'@'=>748,'A'=>684,'B'=>560,'C'=>695,'D'=>739,'E'=>563,
|
||||
'F'=>511,'G'=>729,'H'=>793,'I'=>318,'J'=>312,'K'=>666,'L'=>526,'M'=>896,'N'=>758,'O'=>772,
|
||||
'P'=>544,'Q'=>772,'R'=>628,'S'=>465,'T'=>607,'U'=>753,'V'=>711,'W'=>972,'X'=>647,'Y'=>620,
|
||||
'Z'=>607,'['=>374,'\\'=>333,']'=>374,'^'=>606,'_'=>500,'`'=>239,'a'=>417,'b'=>503,'c'=>427,
|
||||
'd'=>529,'e'=>415,'f'=>264,'g'=>444,'h'=>518,'i'=>241,'j'=>230,'k'=>495,'l'=>228,'m'=>793,
|
||||
'n'=>527,'o'=>524,'p'=>524,'q'=>504,'r'=>338,'s'=>336,'t'=>277,'u'=>517,'v'=>450,'w'=>652,
|
||||
'x'=>466,'y'=>452,'z'=>407,'{'=>370,'|'=>258,'end'=>370,'~'=>605}
|
||||
|
||||
def AddCIDFont(family,style,name,cw,cMap,registry)
|
||||
#ActionController::Base::logger.debug registry.to_a.join(":").to_s
|
||||
fontkey=family.downcase+style.upcase
|
||||
unless @fonts[fontkey].nil?
|
||||
Error("Font already added: family style")
|
||||
end
|
||||
i=@fonts.length+1
|
||||
name=name.gsub(' ','')
|
||||
@fonts[fontkey]={'i'=>i,'type'=>'Type0','name'=>name,'up'=>-130,'ut'=>40,'cw'=>cw, 'CMap'=>cMap,'registry'=>registry}
|
||||
end
|
||||
|
||||
def AddCIDFonts(family,name,cw,cMap,registry)
|
||||
AddCIDFont(family,'',name,cw,cMap,registry)
|
||||
AddCIDFont(family,'B',name+',Bold',cw,cMap,registry)
|
||||
AddCIDFont(family,'I',name+',Italic',cw,cMap,registry)
|
||||
AddCIDFont(family,'BI',name+',BoldItalic',cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddBig5Font(family='Big5',name='MSungStd-Light-Acro')
|
||||
#Add Big5 font with proportional Latin
|
||||
cw=Big5_widths
|
||||
cMap='ETenms-B5-H'
|
||||
registry={'ordering'=>'CNS1','supplement'=>0}
|
||||
#ActionController::Base::logger.debug registry.to_a.join(":").to_s
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddBig5hwFont(family='Big5-hw',name='MSungStd-Light-Acro')
|
||||
#Add Big5 font with half-witdh Latin
|
||||
cw = {}
|
||||
32.upto(126) do |i|
|
||||
cw[i.chr]=500
|
||||
end
|
||||
cMap='ETen-B5-H'
|
||||
registry={'ordering'=>'CNS1','supplement'=>0}
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddGBFont(family='GB',name='STSongStd-Light-Acro')
|
||||
#Add GB font with proportional Latin
|
||||
cw=GB_widths
|
||||
cMap='GBKp-EUC-H'
|
||||
registry={'ordering'=>'GB1','supplement'=>2}
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def AddGBhwFont(family='GB-hw',name='STSongStd-Light-Acro')
|
||||
#Add GB font with half-width Latin
|
||||
32.upto(126) do |i|
|
||||
cw[i.chr]=500
|
||||
end
|
||||
cMap='GBK-EUC-H'
|
||||
registry={'ordering'=>'GB1','supplement'=>2}
|
||||
AddCIDFonts(family,name,cw,cMap,registry)
|
||||
end
|
||||
|
||||
def GetStringWidth(s)
|
||||
if(@CurrentFont['type']=='Type0')
|
||||
return GetMBStringWidth(s)
|
||||
else
|
||||
return super(s)
|
||||
end
|
||||
end
|
||||
|
||||
def GetMBStringWidth(s)
|
||||
#Multi-byte version of GetStringWidth()
|
||||
l=0
|
||||
cw=@CurrentFont['cw']
|
||||
nb=s.length
|
||||
i=0
|
||||
while(i<nb)
|
||||
c=s[i]
|
||||
if(c<128)
|
||||
l+=cw[c.chr] if cw[c.chr]
|
||||
i+=1
|
||||
else
|
||||
l+=1000
|
||||
i+=2
|
||||
end
|
||||
end
|
||||
return l*@FontSize/1000
|
||||
end
|
||||
|
||||
def MultiCell(w,h,txt,border=0,align='L',fill=0)
|
||||
if(@CurrentFont['type']=='Type0')
|
||||
MBMultiCell(w,h,txt,border,align,fill)
|
||||
else
|
||||
super(w,h,txt,border,align,fill)
|
||||
end
|
||||
end
|
||||
|
||||
def MBMultiCell(w,h,txt,border=0,align='L',fill=0)
|
||||
#Multi-byte version of MultiCell()
|
||||
cw=@CurrentFont['cw']
|
||||
if(w==0)
|
||||
w=@w-@rMargin-@x
|
||||
end
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
s=txt.gsub("\r",'')
|
||||
nb=s.length
|
||||
if(nb>0 and s[nb-1]=="\n")
|
||||
nb-=1
|
||||
end
|
||||
b=0
|
||||
if(border)
|
||||
if(border==1)
|
||||
border='LTRB'
|
||||
b='LRT'
|
||||
b2='LR'
|
||||
else
|
||||
b2=''
|
||||
if(border.to_s.index('L'))
|
||||
b2+='L'
|
||||
end
|
||||
if(border.to_s.index('R'))
|
||||
b2+='R'
|
||||
end
|
||||
b=border.to_s.index('T') ? b2+'T' : b2
|
||||
end
|
||||
end
|
||||
sep=-1
|
||||
i=0
|
||||
j=0
|
||||
l=0
|
||||
nl=1
|
||||
while(i<nb)
|
||||
#Get next character
|
||||
c=s[i]
|
||||
#Check if ASCII or MB
|
||||
ascii=(c<128)
|
||||
if(c.chr=="\n")
|
||||
#Explicit line break
|
||||
Cell(w,h,s[j,i-j],b,2,align,fill)
|
||||
i+=1
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
nl+=1
|
||||
if(border and nl==2)
|
||||
b=b2
|
||||
end
|
||||
next
|
||||
end
|
||||
if(!ascii)
|
||||
sep=i
|
||||
ls=l
|
||||
elsif(c==' ')
|
||||
sep=i
|
||||
ls=l
|
||||
end
|
||||
l+=ascii ? (cw[c.chr] || 0) : 1100
|
||||
if(l>wmax)
|
||||
#Automatic line break
|
||||
if(sep==-1 or i==j)
|
||||
if(i==j)
|
||||
i+=ascii ? 1 : 3
|
||||
end
|
||||
Cell(w,h,s[j,i-j],b,2,align,fill)
|
||||
else
|
||||
Cell(w,h,s[j,sep-j],b,2,align,fill)
|
||||
i=(s[sep]==' ') ? sep+1 : sep
|
||||
end
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
# nl+=1
|
||||
if(border and nl==2)
|
||||
b=b2
|
||||
end
|
||||
else
|
||||
i+=ascii ? 1 : 3
|
||||
end
|
||||
end
|
||||
#Last chunk
|
||||
if(border and not border.to_s.index('B').nil?)
|
||||
b+='B'
|
||||
end
|
||||
Cell(w,h,s[j,i-j],b,2,align,fill)
|
||||
@x=@lMargin
|
||||
end
|
||||
|
||||
def Write(h,txt,link='')
|
||||
if(@CurrentFont['type']=='Type0')
|
||||
MBWrite(h,txt,link)
|
||||
else
|
||||
super(h,txt,link)
|
||||
end
|
||||
end
|
||||
|
||||
def MBWrite(h,txt,link)
|
||||
#Multi-byte version of Write()
|
||||
cw=@CurrentFont['cw']
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
s=txt.gsub("\r",'')
|
||||
nb=s.length
|
||||
sep=-1
|
||||
i=0
|
||||
j=0
|
||||
l=0
|
||||
nl=1
|
||||
while(i<nb)
|
||||
#Get next character
|
||||
c=s[i]
|
||||
#Check if ASCII or MB
|
||||
ascii=(c<128)
|
||||
if(c.chr=="\n")
|
||||
#Explicit line break
|
||||
Cell(w,h,s[j,i-j],0,2,'',0,link)
|
||||
i+=1
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
if(nl==1)
|
||||
@x=@lMargin
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
end
|
||||
nl+=1
|
||||
next
|
||||
end
|
||||
if(!ascii or c==' ')
|
||||
sep=i
|
||||
end
|
||||
l+=ascii ? cw[c.chr] : 1100
|
||||
if(l>wmax)
|
||||
#Automatic line break
|
||||
if(sep==-1 or i==j)
|
||||
if(@x>@lMargin)
|
||||
#Move to next line
|
||||
@x=@lMargin
|
||||
@y+=h
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
i+=1
|
||||
nl+=1
|
||||
next
|
||||
end
|
||||
if(i==j)
|
||||
i+=ascii ? 1 : 3
|
||||
end
|
||||
Cell(w,h,s[j,i-j],0,2,'',0,link)
|
||||
else
|
||||
Cell(w,h,s[j,sep-j],0,2,'',0,link)
|
||||
i=(s[sep]==' ') ? sep+1 : sep
|
||||
end
|
||||
sep=-1
|
||||
j=i
|
||||
l=0
|
||||
if(nl==1)
|
||||
@x=@lMargin
|
||||
w=@w-@rMargin-@x
|
||||
wmax=(w-2*@cMargin)*1000/@FontSize
|
||||
end
|
||||
nl+=1
|
||||
else
|
||||
i+=ascii ? 1 : 3
|
||||
end
|
||||
end
|
||||
#Last chunk
|
||||
if(i!=j)
|
||||
Cell(l/1000*@FontSize,h,s[j,i-j],0,0,'',0,link)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def putfonts()
|
||||
nf=@n
|
||||
@diffs.each do |diff|
|
||||
#Encodings
|
||||
newobj()
|
||||
out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['+diff+']>>')
|
||||
out('endobj')
|
||||
end
|
||||
# mqr=get_magic_quotes_runtime()
|
||||
# set_magic_quotes_runtime(0)
|
||||
@FontFiles.each_pair do |file, info|
|
||||
#Font file embedding
|
||||
newobj()
|
||||
@FontFiles[file]['n']=@n
|
||||
if(defined('FPDF_FONTPATH'))
|
||||
file=FPDF_FONTPATH+file
|
||||
end
|
||||
size=filesize(file)
|
||||
if(!size)
|
||||
Error('Font file not found')
|
||||
end
|
||||
out('<</Length '+size)
|
||||
if(file[-2]=='.z')
|
||||
out('/Filter /FlateDecode')
|
||||
end
|
||||
out('/Length1 '+info['length1'])
|
||||
unless info['length2'].nil?
|
||||
out('/Length2 '+info['length2']+' /Length3 0')
|
||||
end
|
||||
out('>>')
|
||||
f=fopen(file,'rb')
|
||||
putstream(fread(f,size))
|
||||
fclose(f)
|
||||
out('endobj')
|
||||
end
|
||||
#
|
||||
# set_magic_quotes_runtime(mqr)
|
||||
#
|
||||
@fonts.each_pair do |k, font|
|
||||
#Font objects
|
||||
newobj()
|
||||
@fonts[k]['n']=@n
|
||||
out('<</Type /Font')
|
||||
if(font['type']=='Type0')
|
||||
putType0(font)
|
||||
else
|
||||
name=font['name']
|
||||
out('/BaseFont /'+name)
|
||||
if(font['type']=='core')
|
||||
#Standard font
|
||||
out('/Subtype /Type1')
|
||||
if(name!='Symbol' and name!='ZapfDingbats')
|
||||
out('/Encoding /WinAnsiEncoding')
|
||||
end
|
||||
else
|
||||
#Additional font
|
||||
out('/Subtype /'+font['type'])
|
||||
out('/FirstChar 32')
|
||||
out('/LastChar 255')
|
||||
out('/Widths '+(@n+1)+' 0 R')
|
||||
out('/FontDescriptor '+(@n+2)+' 0 R')
|
||||
if(font['enc'])
|
||||
if !font['diff'].nil?
|
||||
out('/Encoding '+(nf+font['diff'])+' 0 R')
|
||||
else
|
||||
out('/Encoding /WinAnsiEncoding')
|
||||
end
|
||||
end
|
||||
end
|
||||
out('>>')
|
||||
out('endobj')
|
||||
if(font['type']!='core')
|
||||
#Widths
|
||||
newobj()
|
||||
cw=font['cw']
|
||||
s='['
|
||||
32.upto(255) do |i|
|
||||
s+=cw[i.chr]+' '
|
||||
end
|
||||
out(s+']')
|
||||
out('endobj')
|
||||
#Descriptor
|
||||
newobj()
|
||||
s='<</Type /FontDescriptor /FontName /'+name
|
||||
font['desc'].each_pair do |k, v|
|
||||
s+=' /'+k+' '+v
|
||||
end
|
||||
file=font['file']
|
||||
if(file)
|
||||
s+=' /FontFile'+(font['type']=='Type1' ? '' : '2')+' '+@FontFiles[file]['n']+' 0 R'
|
||||
end
|
||||
out(s+'>>')
|
||||
out('endobj')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def putType0(font)
|
||||
#Type0
|
||||
out('/Subtype /Type0')
|
||||
out('/BaseFont /'+font['name']+'-'+font['CMap'])
|
||||
out('/Encoding /'+font['CMap'])
|
||||
out('/DescendantFonts ['+(@n+1).to_s+' 0 R]')
|
||||
out('>>')
|
||||
out('endobj')
|
||||
#CIDFont
|
||||
newobj()
|
||||
out('<</Type /Font')
|
||||
out('/Subtype /CIDFontType0')
|
||||
out('/BaseFont /'+font['name'])
|
||||
out('/CIDSystemInfo <</Registry '+textstring('Adobe')+' /Ordering '+textstring(font['registry']['ordering'])+' /Supplement '+font['registry']['supplement'].to_s+'>>')
|
||||
out('/FontDescriptor '+(@n+1).to_s+' 0 R')
|
||||
if(font['CMap']=='ETen-B5-H')
|
||||
w='13648 13742 500'
|
||||
elsif(font['CMap']=='GBK-EUC-H')
|
||||
w='814 907 500 7716 [500]'
|
||||
else
|
||||
# ActionController::Base::logger.debug font['cw'].keys.sort.join(' ').to_s
|
||||
# ActionController::Base::logger.debug font['cw'].values.join(' ').to_s
|
||||
w='1 ['
|
||||
font['cw'].keys.sort.each {|key|
|
||||
w+=font['cw'][key].to_s + " "
|
||||
# ActionController::Base::logger.debug key.to_s
|
||||
# ActionController::Base::logger.debug font['cw'][key].to_s
|
||||
}
|
||||
w +=']'
|
||||
end
|
||||
out('/W ['+w+']>>')
|
||||
out('endobj')
|
||||
#Font descriptor
|
||||
newobj()
|
||||
out('<</Type /FontDescriptor')
|
||||
out('/FontName /'+font['name'])
|
||||
out('/Flags 6')
|
||||
out('/FontBBox [0 -200 1000 900]')
|
||||
out('/ItalicAngle 0')
|
||||
out('/Ascent 800')
|
||||
out('/Descent -200')
|
||||
out('/CapHeight 800')
|
||||
out('/StemV 50')
|
||||
out('>>')
|
||||
out('endobj')
|
||||
end
|
||||
end
|
||||
|
||||
+11
-1
@@ -30,6 +30,8 @@
|
||||
module RFPDF
|
||||
|
||||
class View
|
||||
@@backward_compatibility_mode = false
|
||||
cattr_accessor :backward_compatibility_mode
|
||||
|
||||
def initialize(action_view)
|
||||
@action_view = action_view
|
||||
@@ -45,6 +47,14 @@ module RFPDF
|
||||
:temp_dir => "#{File.expand_path(RAILS_ROOT)}/tmp"
|
||||
}.merge(@action_view.controller.instance_eval{ @options_for_rfpdf } || {}).with_indifferent_access
|
||||
end
|
||||
|
||||
def self.compilable?
|
||||
false
|
||||
end
|
||||
|
||||
def compilable?
|
||||
self.class.compilable?
|
||||
end
|
||||
|
||||
def render(template, local_assigns = {})
|
||||
@pdf_name = "Default.pdf" if @pdf_name.nil?
|
||||
@@ -66,7 +76,7 @@ module RFPDF
|
||||
local_assigns.each do |key,val|
|
||||
class << self; self; end.send(:define_method,key){ val }
|
||||
end
|
||||
ERB.new(template).result(binding)
|
||||
ERB.new(@@backward_compatibility_mode == true ? template : template.source).result(binding)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
Reference in New Issue
Block a user