Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Remove all methods and features deprecated in 2.12

This huge commit removes the deprecated code and deprecated specs
(over 300!).  It also makes some other minor changes.

Sequel.virtual_row_instance_eval is now true, but setting it to false
does nothing.  Using instance_eval for virtual row blocks that don't
accept arguments is now standard Sequel behavior.

Some error messages in convenience.rb were turned into constants to
reduce garbaged produced.  More work on this will probably be done in
the future.

Dataset#import was using each_slice, which was probably provided by
enumerator.  Change to using a loop and slicing manually.

The built in inflector now calls the string inflection methods if
the string responds to the method.  The inflector extension no longer
updates the built in inflector, since it no longer needs to.

Database#blank_object? calls blank? on the object if the object
responds to it.

The connection pool had a slight code refactoring to make things
easier to read.

The hook_class_methods plugin instance methods call super, so using
the plugin doesn't ignore previous instance level hooks.  Among other
things, this allows you to use the hook_class_methods plugin after
the caching plugin, which fixes #264.

Make the serialization plugin test require yaml, since it
uses yaml.  This only seems necessary on ruby 1.9.

Sequel::Deprecation is being moved to the extra directory.  I'm
moving it out of lib so it won't show up in the RDoc.  I'm not
removing it completely because I expect it may be used again
sometime in the future.

One thing that I realize that I should have officially deprecated
was the 4th argument to join_table being a table_alias instead of a
hash of options.  So Sequel will continue to support that.
  • Loading branch information...
commit ac1976a8c9079728666337a802f469ebe854d4f1 1 parent 38a57ce
@jeremyevans authored
Showing with 164 additions and 5,827 deletions.
  1. +38 −0 extra/deprecated.rb
  2. +0 −4 lib/sequel/adapters/do.rb
  3. +0 −4 lib/sequel/adapters/firebird.rb
  4. +0 −12 lib/sequel/adapters/jdbc.rb
  5. +4 −8 lib/sequel/adapters/mysql.rb
  6. +0 −4 lib/sequel/adapters/odbc.rb
  7. +0 −4 lib/sequel/adapters/oracle.rb
  8. +8 −37 lib/sequel/adapters/shared/mysql.rb
  9. +0 −4 lib/sequel/adapters/shared/postgres.rb
  10. +2 −8 lib/sequel/adapters/shared/sqlite.rb
  11. +0 −4 lib/sequel/adapters/sqlite.rb
  12. +3 −1 lib/sequel/connection_pool.rb
  13. +2 −21 lib/sequel/core.rb
  14. +13 −43 lib/sequel/database.rb
  15. +14 −41 lib/sequel/dataset.rb
  16. +31 −54 lib/sequel/dataset/convenience.rb
  17. +7 −13 lib/sequel/dataset/graph.rb
  18. +12 −20 lib/sequel/dataset/sql.rb
  19. +0 −593 lib/sequel/deprecated.rb
  20. +0 −91 lib/sequel/deprecated_migration.rb
  21. +0 −5 lib/sequel/extensions/inflector.rb
  22. +1 −2  lib/sequel/model.rb
  23. +1 −9 lib/sequel/model/base.rb
  24. +0 −204 lib/sequel/model/deprecated.rb
  25. +0 −103 lib/sequel/model/deprecated_hooks.rb
  26. +0 −335 lib/sequel/model/deprecated_inflector.rb
  27. +0 −388 lib/sequel/model/deprecated_validations.rb
  28. +6 −9 lib/sequel/model/inflections.rb
  29. +1 −1  lib/sequel/plugins/hook_class_methods.rb
  30. +0 −156 spec/core/core_ext_spec.rb
  31. +0 −166 spec/core/core_sql_spec.rb
  32. +0 −132 spec/core/database_spec.rb
  33. +16 −908 spec/core/dataset_spec.rb
  34. +0 −263 spec/core/migration_spec.rb
  35. +0 −58 spec/core/pretty_table_spec.rb
  36. +0 −16 spec/core/schema_spec.rb
  37. +0 −25 spec/core/spec_helper.rb
  38. +2 −0  spec/extensions/serialization_spec.rb
  39. +0 −2  spec/extensions/spec_helper.rb
  40. +0 −12 spec/integration/schema_test.rb
  41. +0 −14 spec/integration/spec_helper.rb
  42. +0 −36 spec/model/associations_spec.rb
  43. +0 −106 spec/model/base_spec.rb
  44. +0 −217 spec/model/caching_spec.rb
  45. +2 −235 spec/model/hooks_spec.rb
  46. +0 −126 spec/model/inflector_spec.rb
  47. +0 −120 spec/model/model_spec.rb
  48. +0 −70 spec/model/plugins_spec.rb
  49. +1 −93 spec/model/record_spec.rb
  50. +0 −92 spec/model/schema_spec.rb
  51. +0 −27 spec/model/spec_helper.rb
  52. +0 −931 spec/model/validations_spec.rb
View
38 extra/deprecated.rb
@@ -0,0 +1,38 @@
+module Sequel
+ # This module makes it easy to print deprecation warnings with optional backtraces to a given stream.
+ # There are a couple of methods you can use to change where the deprecation methods are printed
+ # and whether they should include backtraces:
+ #
+ # Sequel::Deprecation.output = $stderr # print deprecation messages to standard error (default)
+ # Sequel::Deprecation.output = File.open('deprecated_calls.txt', 'wb') # use a file instead
+ # Sequel::Deprecation.backtraces = false # don't include backtraces
+ # Sequel::Deprecation.backtraces = true # include full backtraces
+ # Sequel::Deprecation.backtraces = 10 # include 10 backtrace lines (default)
+ # Sequel::Deprecation.backtraces = 1 # include 1 backtrace line
+ module Deprecation
+ extend Metaprogramming
+
+ @output = $stderr
+ @backtraces = 10
+
+ metaattr_accessor :output, :backtraces
+
+ # Print the message to the output stream
+ def self.deprecate(method, instead=nil)
+ message = instead ? "#{method} is deprecated and will be removed in Sequel 3.0. #{instead}." : method
+ return unless output
+ output.puts(message)
+ case backtraces
+ when Integer
+ b = backtraces
+ caller.each do |c|
+ b -= 1
+ output.puts(c)
+ break if b == 0
+ end
+ when true
+ caller.each{|c| output.puts(c)}
+ end
+ end
+ end
+end
View
4 lib/sequel/adapters/do.rb
@@ -121,10 +121,6 @@ def subadapter
# transactions and commits them immediately after. It's wasteful,
# but required by DataObject's API.
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
th = Thread.current
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(th)
View
4 lib/sequel/adapters/firebird.rb
@@ -106,10 +106,6 @@ def tables(opts={})
end
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current)
log_info("Transaction.begin")
View
12 lib/sequel/adapters/jdbc.rb
@@ -197,10 +197,6 @@ def tables
# databases. Does not use the JDBC transaction methods, uses
# SQL BEGIN/ROLLBACK/COMMIT statements instead.
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current)
stmt = conn.createStatement
@@ -476,11 +472,3 @@ def process_result_set(result)
end
end
end
-
-class Java::JavaSQL::Timestamp
- # Add a usec method in order to emulate Time values.
- def usec
- Deprecation.deprecate('Java::JavaSQL::Timestamp#usec', 'Use timestamp.getNanos/1000')
- getNanos/1000
- end
-end
View
12 lib/sequel/adapters/mysql.rb
@@ -135,10 +135,6 @@ def server_version(server=nil)
# Support single level transactions on MySQL.
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current)
log_info(begin_transaction_sql)
@@ -297,8 +293,8 @@ def call(type, bind_arguments={}, values=nil)
end
# Delete rows matching this dataset
- def delete(opts = (defarg=true;nil))
- execute_dui(defarg ? delete_sql : delete_sql(opts)){|c| c.affected_rows}
+ def delete
+ execute_dui(delete_sql){|c| c.affected_rows}
end
# Yield all rows matching this dataset
@@ -338,8 +334,8 @@ def replace(*args)
end
# Update the matching rows.
- def update(values={}, opts=(defarg=true;nil))
- execute_dui(defarg ? update_sql(values) : update_sql(values, opts)){|c| c.affected_rows}
+ def update(values={})
+ execute_dui(update_sql(values)){|c| c.affected_rows}
end
private
View
4 lib/sequel/adapters/odbc.rb
@@ -65,10 +65,6 @@ def execute_dui(sql, opts={})
# Support single level transactions on ODBC
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current)
log_info(begin_transaction_sql)
View
4 lib/sequel/adapters/oracle.rb
@@ -78,10 +78,6 @@ def execute(sql, opts={})
alias do execute
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current)
conn.autocommit = false
View
45 lib/sequel/adapters/shared/mysql.rb
@@ -175,22 +175,10 @@ def complex_expression_sql(op, args)
end
# MySQL supports ORDER and LIMIT clauses in DELETE statements.
- def delete_sql(opts = (defarg=true;nil))
- if defarg
- sql = super()
- opts = @opts
- else
- sql = super
- opts = opts ? @opts.merge(opts) : @opts
- end
-
- if order = opts[:order]
- sql << " ORDER BY #{expression_list(order)}"
- end
- if limit = opts[:limit]
- sql << " LIMIT #{limit}"
- end
-
+ def delete_sql
+ sql = super
+ sql << " ORDER BY #{expression_list(opts[:order])}" if opts[:order]
+ sql << " LIMIT #{opts[:limit]}" if opts[:limit]
sql
end
@@ -311,11 +299,6 @@ def replace_sql(*values)
else
values = values[0] if values.size == 1
- # if hash or array with keys we need to transform the values
- if @transform && (values.is_a?(Hash) || (values.is_a?(Array) && values.keys))
- values = transform_save(values)
- end
-
case values
when Array
if values.empty?
@@ -344,22 +327,10 @@ def replace_sql(*values)
end
# MySQL supports ORDER and LIMIT clauses in UPDATE statements.
- def update_sql(values, opts = (defarg=true;nil))
- if defarg
- sql = super(values)
- opts = @opts
- else
- sql = super
- opts = opts ? @opts.merge(opts) : @opts
- end
-
- if order = opts[:order]
- sql << " ORDER BY #{expression_list(order)}"
- end
- if limit = opts[:limit]
- sql << " LIMIT #{limit}"
- end
-
+ def update_sql(values)
+ sql = super
+ sql << " ORDER BY #{expression_list(opts[:order])}" if opts[:order]
+ sql << " LIMIT #{opts[:limit]}" if opts[:limit]
sql
end
View
4 lib/sequel/adapters/shared/postgres.rb
@@ -338,10 +338,6 @@ def tables(opts={})
# To use a savepoint instead of reusing the current transaction,
# use the :savepoint=>true option.
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current) and !opts[:savepoint]
conn.transaction_depth ||= 0
View
10 lib/sequel/adapters/shared/sqlite.rb
@@ -217,14 +217,8 @@ def complex_expression_sql(op, args)
# SQLite performs a TRUNCATE style DELETE if no filter is specified.
# Since we want to always return the count of records, add a condition
# that is always true and then delete.
- def delete(opts = (defarg=true;{}))
- # check if no filter is specified
- if defarg
- @opts[:where] ? super() : filter(1=>1).delete
- else
- opts = @opts.merge(opts)
- super(opts[:where] ? opts : opts.merge(:where=>{1=>1}))
- end
+ def delete
+ @opts[:where] ? super : filter(1=>1).delete
end
# Insert the values into the database.
View
4 lib/sequel/adapters/sqlite.rb
@@ -87,10 +87,6 @@ def single_value(sql, opts={})
# in progress on the connection, always yielding a connection inside a transaction
# transaction.
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if conn.transaction_active?
begin
View
4 lib/sequel/connection_pool.rb
@@ -114,8 +114,10 @@ def hold(server=:default)
ensure
release(t, conn, server) unless dde
end
+ rescue StandardError => e
+ raise e
rescue Exception => e
- raise(@convert_exceptions && !e.is_a?(StandardError) ? RuntimeError.new(e.message) : e)
+ raise(@convert_exceptions ? RuntimeError.new(e.message) : e)
end
end
View
23 lib/sequel/core.rb
@@ -34,32 +34,13 @@
#
# Sequel.datetime_class = DateTime
#
-# Sequel currently does not use instance_eval for virtual row blocks by default
-# (e.g. the block passed to Dataset#filter, #select, #order and other similar
-# methods). If you want to use instance_eval for these blocks, don't have any
-# block arguments, and set:
-#
-# Sequel.virtual_row_instance_eval = true
-#
-# When this is set, you can do:
-#
-# dataset.filter{|o| o.column > 0} # no instance_eval
-# dataset.filter{column > 0} # instance eval
-#
-# When the virtual_row_instance_eval is false, using a virtual row block without a block
-# argument will generate a deprecation message.
-#
-# The option to not use instance_eval for a block with no arguments will be removed in Sequel 3.0.
-# If you have any virtual row blocks that you don't want to use instance_eval for,
-# make sure the blocks have block arguments.
-#
# You can set the SEQUEL_NO_CORE_EXTENSIONS constant or environment variable to have
# Sequel not extend the core classes.
module Sequel
@convert_tinyint_to_bool = true
@convert_two_digit_years = true
@datetime_class = Time
- @virtual_row_instance_eval = false
+ @virtual_row_instance_eval = true
class << self
attr_accessor :convert_tinyint_to_bool, :convert_two_digit_years, :datetime_class, :virtual_row_instance_eval
@@ -211,7 +192,7 @@ def self.def_adapter_method(*adapters) # :nodoc:
private_class_method :adapter_method, :def_adapter_method
- require(%w"metaprogramming sql connection_pool exceptions dataset database version deprecated")
+ require(%w"metaprogramming sql connection_pool exceptions dataset database version")
require(%w"schema_generator schema_methods schema_sql", 'database')
require(%w"convenience graph prepared_statements sql", 'dataset')
require('core_sql') if !defined?(::SEQUEL_NO_CORE_EXTENSIONS) && !ENV.has_key?('SEQUEL_NO_CORE_EXTENSIONS')
View
56 lib/sequel/database.rb
@@ -77,10 +77,6 @@ def initialize(opts = {}, &block)
@identifier_input_method = nil
@identifier_output_method = nil
@quote_identifiers = nil
- if opts.include?(:upcase_identifiers)
- Deprecation.deprecate('The :upcase_identifiers Database option', 'Use the :identifier_input_method => :upcase option instead')
- @identifier_input_method = opts[:upcase_identifiers] ? :upcase : ""
- end
@pool = (@single_threaded ? SingleThreadedPool : ConnectionPool).new(connection_pool_default_options.merge(opts), &block)
@pool.connection_proc = proc{|server| connect(server)} unless block
@pool.disconnection_proc = proc{|conn| disconnect_connection(conn)} unless opts[:disconnection_proc]
@@ -225,8 +221,7 @@ def self.uri_to_options(uri) # :nodoc:
# Executes the supplied SQL statement string.
def <<(sql)
- Deprecation.deprecate('Passing an array argument to Database#<<', 'Use array.each{|x| database << x}') if Array === sql
- execute_ddl((Array === sql) ? sql.to_sql : sql)
+ execute_ddl(sql)
end
# Returns a dataset from the database. If the first argument is a string,
@@ -409,9 +404,9 @@ def select(*args, &block)
end
# Parse the schema from the database.
- # If the table_name is not given, returns the schema for all tables as a hash.
- # If the table_name is given, returns the schema for a single table as an
- # array with all members being arrays of length 2. Available options are:
+ # Returns the schema for the given table as an array with all members being arrays of length 2,
+ # the first member being the column name, and the second member being a hash of column information.
+ # Available options are:
#
# * :reload - Get fresh information from the database, instead of using
# cached information. If table_name is blank, :reload should be used
@@ -420,46 +415,24 @@ def select(*args, &block)
# that have been requested explicitly.
# * :schema - An explicit schema to use. It may also be implicitly provided
# via the table name.
- def schema(table = nil, opts={})
- Deprecation.deprecate('Calling Database#schema without a table argument', 'Use database.tables.inject({}){|h, m| h[m] = database.schema(m); h}') unless table
+ def schema(table, opts={})
raise(Error, 'schema parsing is not implemented on this database') unless respond_to?(:schema_parse_table, true)
- if table
- sch, table_name = schema_and_table(table)
- quoted_name = quote_schema_table(table)
- end
+ sch, table_name = schema_and_table(table)
+ quoted_name = quote_schema_table(table)
opts = opts.merge(:schema=>sch) if sch && !opts.include?(:schema)
- if opts[:reload] && @schemas
- if table_name
- @schemas.delete(quoted_name)
- else
- @schemas = nil
- end
- end
-
- if @schemas
- if table_name
- return @schemas[quoted_name] if @schemas[quoted_name]
- else
- return @schemas
- end
- end
- raise(Error, '#tables does not exist, you must provide a specific table to #schema') if table.nil? && !respond_to?(:tables, true)
+ @schemas.delete(quoted_name) if opts[:reload] && @schemas
+ return @schemas[quoted_name] if @schemas && @schemas[quoted_name]
@schemas ||= Hash.new do |h,k|
quote_name = quote_schema_table(k)
h[quote_name] if h.include?(quote_name)
end
- if table_name
- cols = schema_parse_table(table_name, opts)
- raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
- @schemas[quoted_name] = cols
- else
- tables.each{|t| @schemas[quote_schema_table(t)] = schema_parse_table(t.to_s, opts)}
- @schemas
- end
+ cols = schema_parse_table(table_name, opts)
+ raise(Error, 'schema parsing returned no columns, table probably doesn\'t exist') if cols.nil? || cols.empty?
+ @schemas[quoted_name] = cols
end
# Returns true if the database is using a single-threaded connection pool.
@@ -500,10 +473,6 @@ def test_connection(server=nil)
# current transaction. Should be overridden for databases that support nested
# transactions.
def transaction(opts={})
- unless opts.is_a?(Hash)
- Deprecation.deprecate('Passing an argument other than a Hash to Database#transaction', "Use DB.transaction(:server=>#{opts.inspect})")
- opts = {:server=>opts}
- end
synchronize(opts[:server]) do |conn|
return yield(conn) if @transactions.include?(Thread.current)
log_info(begin_transaction_sql)
@@ -579,6 +548,7 @@ def begin_transaction_sql
# strings with all whitespace, and ones that respond
# true to empty?
def blank_object?(obj)
+ return obj.blank? if obj.respond_to?(:blank?)
case obj
when NilClass, FalseClass
true
View
55 lib/sequel/dataset.rb
@@ -87,7 +87,6 @@ def initialize(db, opts = nil)
@identifier_output_method = db.identifier_output_method if db.respond_to?(:identifier_output_method)
@opts = opts || {}
@row_proc = nil
- @transform = nil
end
### Class Methods ###
@@ -118,10 +117,9 @@ def as(aliaz)
# Returns an array with all records in the dataset. If a block is given,
# the array is iterated over after all items have been loaded.
- def all(opts = (defarg=true;nil), &block)
- Deprecation.deprecate("Calling Dataset#all with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).all.") unless defarg
+ def all(&block)
a = []
- defarg ? each{|r| a << r} : each(opts){|r| a << r}
+ each{|r| a << r}
post_load(a)
a.each(&block) if block
a
@@ -170,24 +168,21 @@ def def_mutation_method(*meths)
# Deletes the records in the dataset. The returned value is generally the
# number of records deleted, but that is adapter dependent.
- def delete(opts=(defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#delete with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).delete.") unless defarg
- execute_dui(defarg ? delete_sql : delete_sql(opts))
+ def delete
+ execute_dui(delete_sql)
end
# Iterates over the records in the dataset as they are yielded from the
# database adapter, and returns self.
- def each(opts = (defarg=true;nil), &block)
- Deprecation.deprecate("Calling Dataset#each with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).each.") unless defarg
- if opts && opts.keys.any?{|o| COLUMN_CHANGE_OPTS.include?(o)}
- prev_columns = @columns
- begin
- defarg ? _each(&block) : _each(opts, &block)
- ensure
- @columns = prev_columns
- end
+ def each(&block)
+ if @opts[:graph]
+ graph_each(&block)
else
- defarg ? _each(&block) : _each(opts, &block)
+ if row_proc = @row_proc
+ fetch_rows(select_sql){|r| yield row_proc.call(r)}
+ else
+ fetch_rows(select_sql, &block)
+ end
end
self
end
@@ -250,9 +245,8 @@ def set_overrides(hash)
# Updates values for the dataset. The returned value is generally the
# number of rows updated, but that is adapter dependent.
- def update(values={}, opts=(defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#update with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).update.") unless defarg
- execute_dui(defarg ? update_sql(values) : update_sql(value, opts))
+ def update(values={})
+ execute_dui(update_sql(values))
end
# Add the mutation methods via metaprogramming
@@ -267,23 +261,6 @@ def options_overlap(opts)
private
- # Runs #graph_each if graphing. Otherwise, iterates through the records
- # yielded by #fetch_rows, applying any row_proc or transform if necessary,
- # and yielding the result.
- def _each(opts=(defarg=true;nil), &block)
- if @opts[:graph] and !(opts && opts[:graph] == false)
- defarg ? graph_each(&block) : graph_each(opts, &block)
- else
- row_proc = @row_proc unless opts && opts[:naked]
- transform = @transform
- fetch_rows(defarg ? select_sql : select_sql(opts)) do |r|
- r = transform_load(r) if transform
- r = row_proc[r] if row_proc
- yield r
- end
- end
- end
-
# Set the server to use to :default unless it is already set in the passed opts
def default_server_opts(opts)
{:server=>@opts[:server] || :default}.merge(opts)
@@ -338,10 +315,6 @@ def post_load(all_records)
# VirtualRow instance.
def virtual_row_block_call(block)
return unless block
- unless Sequel.virtual_row_instance_eval
- Deprecation.deprecate('Using a VirtualRow block without an argument is deprecated, and its meaning will change in Sequel 3.0. Add a block argument to keep the old semantics, or set Sequel.virtual_row_instance_eval = true to use instance_eval for VirtualRow blocks without arguments.') unless block.arity == 1
- return block.call(SQL::VirtualRow.new)
- end
case block.arity
when -1, 0
SQL::VirtualRow.new.instance_eval(&block)
View
85 lib/sequel/dataset/convenience.rb
@@ -2,13 +2,16 @@ module Sequel
class Dataset
COMMA_SEPARATOR = ', '.freeze
COUNT_OF_ALL_AS_COUNT = SQL::Function.new(:count, LiteralString.new('*'.freeze)).as(:count)
+ ARRAY_ACCESS_ERROR_MSG = 'You cannot call Dataset#[] with an integer or with no arguments.'.freeze
+ MAP_ERROR_MSG = 'Using Dataset#map with an argument and a block is not allowed'.freeze
+ GET_ERROR_MSG = 'must provide argument or block to Dataset#get, not both'.freeze
+ IMPORT_ERROR_MSG = 'Using Sequel::Dataset#import an empty column array is not allowed'.freeze
# Returns the first record matching the conditions. Examples:
#
# ds[:id=>1] => {:id=1}
def [](*conditions)
- Deprecation.deprecate('Using an Integer argument to Dataset#[] is deprecated and will raise an error in Sequel 3.0. Use Dataset#first.') if conditions.length == 1 and conditions.is_a?(Integer)
- Deprecation.deprecate('Using Dataset#[] without an argument is deprecated and will raise an error in Sequel 3.0. Use Dataset#first.') if conditions.length == 0
+ raise(Error, ARRAY_ACCESS_ERROR_MSG) if (conditions.length == 1 and conditions.is_a?(Integer)) or conditions.length == 0
first(*conditions)
end
@@ -70,8 +73,12 @@ def first(*args, &block)
# ds.get(:id)
# ds.get{|o| o.sum(:id)}
def get(column=nil, &block)
- raise(Error, 'must provide argument or block to Dataset#get, not both') if column && block
- (column ? select(column) : select(&block)).single_value
+ if column
+ raise(Error, GET_ERROR_MSG) if block
+ select(column).single_value
+ else
+ select(&block).single_value
+ end
end
# Returns a dataset grouped by the given column with count by group,
@@ -101,31 +108,18 @@ def group_and_count(*columns)
#
# # this will commit every 50 records
# dataset.import([:x, :y], [[1, 2], [3, 4], ...], :slice => 50)
- def import(*args)
- if args.empty?
- Sequel::Deprecation.deprecate('Calling Sequel::Dataset#import with no arguments', 'Use dataset.multi_insert([])')
- return
- elsif args[0].is_a?(Array) && args[1].is_a?(Array)
- columns, values, opts = *args
- elsif args[0].is_a?(Array) && args[1].is_a?(Dataset)
- table = @opts[:from].first
- columns, dataset = *args
- sql = "INSERT INTO #{quote_identifier(table)} (#{identifier_list(columns)}) VALUES #{literal(dataset)}"
- return @db.transaction{execute_dui(sql)}
- else
- Sequel::Deprecation.deprecate('Calling Sequel::Dataset#import with hashes', 'Use Sequel::Dataset#multi_insert')
- return multi_insert(*args)
- end
- # make sure there's work to do
- Sequel::Deprecation.deprecate('Calling Sequel::Dataset#import an empty column array is deprecated and will raise an error in Sequel 3.0.') if columns.empty?
- return if columns.empty? || values.empty?
-
- slice_size = opts && (opts[:commit_every] || opts[:slice])
+ def import(columns, values, opts={})
+ return @db.transaction{execute_dui("INSERT INTO #{quote_schema_table(@opts[:from].first)} (#{identifier_list(columns)}) VALUES #{literal(values)}")} if values.is_a?(Dataset)
+
+ return if values.empty?
+ raise(Error, IMPORT_ERROR_MSG) if columns.empty?
- if slice_size
- values.each_slice(slice_size) do |slice|
- statements = multi_insert_sql(columns, slice)
- @db.transaction(opts){statements.each{|st| execute_dui(st)}}
+ if slice_size = opts[:commit_every] || opts[:slice]
+ offset = 0
+ loop do
+ @db.transaction(opts){multi_insert_sql(columns, values[offset, slice_size]).each{|st| execute_dui(st)}}
+ offset += slice_size
+ break if offset >= values.length
end
else
statements = multi_insert_sql(columns, values)
@@ -155,8 +149,8 @@ def last(*args, &block)
# ds.map(:id) => [1, 2, 3, ...]
# ds.map{|r| r[:id] * 2} => [2, 4, 6, ...]
def map(column=nil, &block)
- Deprecation.deprecate('Using Dataset#map with an argument and a block is deprecated and will raise an error in Sequel 3.0. Use an argument or a block, not both.') if column && block
if column
+ raise(Error, MAP_ERROR_MSG) if block
super(){|r| r[column]}
else
super(&block)
@@ -183,22 +177,10 @@ def min(column)
# values.
#
# You can also use the :slice or :commit_every option that import accepts.
- def multi_insert(*args)
- if args.empty?
- Sequel::Deprecation.deprecate('Calling Sequel::Dataset#multi_insert with no arguments', 'Use dataset.multi_insert([])')
- return
- elsif args[0].is_a?(Array) && (args[1].is_a?(Array) || args[1].is_a?(Dataset))
- Sequel::Deprecation.deprecate('Calling Sequel::Dataset#multi_insert with an array of columns and an array of arrays of values', 'Use Sequel::Dataset#import')
- return import(*args)
- else
- # we assume that an array of hashes is given
- hashes, opts = *args
- return if hashes.empty?
- columns = hashes.first.keys
- # convert the hashes into arrays
- values = hashes.map {|h| columns.map {|c| h[c]}}
- end
- import(columns, values, opts)
+ def multi_insert(hashes, opts={})
+ return if hashes.empty?
+ columns = hashes.first.keys
+ import(columns, hashes.map{|h| columns.map{|c| h[c]}}, opts)
end
# Returns a Range object made from the minimum and maximum values for the
@@ -210,20 +192,15 @@ def range(column)
end
# Returns the first record in the dataset.
- def single_record(opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#single_record with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).single_record.") unless defarg
- ds = clone(:limit=>1)
- opts = opts.merge(:limit=>1) if opts and opts[:limit]
- defarg ? ds.each{|r| return r} : ds.each(opts){|r| return r}
+ def single_record
+ clone(:limit=>1).each{|r| return r}
nil
end
# Returns the first value of the first record in the dataset.
# Returns nil if dataset is empty.
- def single_value(opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#single_value with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).single_value.") unless defarg
- ds = naked.clone(:graph=>false)
- if r = (defarg ? ds.single_record : ds.single_record(opts))
+ def single_value
+ if r = naked.clone(:graph=>false).single_record
r.values.first
end
end
View
20 lib/sequel/dataset/graph.rb
@@ -17,8 +17,7 @@ class Dataset
# the tables are combined in the single return hash. You can get around that by
# using .select with correct aliases for all of the columns, but it is simpler to
# use graph and have the result set split for you. In addition, graph respects
- # any row_proc or transform attributes of the current dataset and the datasets
- # you use with graph.
+ # any row_proc of the current dataset and the datasets you use with graph.
#
# If you are graphing a table and all columns for that table are nil, this
# indicates that no matching rows existed in the table, so graph will return nil
@@ -186,7 +185,7 @@ def graph_alias_columns(graph_aliases)
# Fetch the rows, split them into component table parts,
# tranform and run the row_proc on each part (if applicable),
# and yield a hash of the parts.
- def graph_each(opts=(defarg=true;nil), &block)
+ def graph_each
# Reject tables with nil datasets, as they are excluded from
# the result set
datasets = @opts[:graph][:table_aliases].to_a.reject{|ta,ds| ds.nil?}
@@ -194,13 +193,11 @@ def graph_each(opts=(defarg=true;nil), &block)
table_aliases = datasets.collect{|ta,ds| ta}
# Get an array of arrays, one for each dataset, with
# the necessary information about each dataset, for speed
- datasets = datasets.collect do |ta, ds|
- [ta, ds, ds.instance_variable_get(:@transform), ds.row_proc]
- end
+ datasets = datasets.collect{|ta, ds| [ta, ds, ds.row_proc]}
# Use the manually set graph aliases, if any, otherwise
# use the ones automatically created by .graph
column_aliases = @opts[:graph_aliases] || @opts[:graph][:column_aliases]
- fetch_rows(defarg ? select_sql : select_sql(opts)) do |r|
+ fetch_rows(select_sql) do |r|
graph = {}
# Create the sub hashes, one per table
table_aliases.each{|ta| graph[ta]={}}
@@ -211,14 +208,11 @@ def graph_each(opts=(defarg=true;nil), &block)
ta, column = tc
graph[ta][column] = r[col_alias]
end
- # For each dataset, transform and run the row
- # row_proc if applicable
- datasets.each do |ta,ds,tr,rp|
+ # For each dataset run the row_proc if applicable
+ datasets.each do |ta,ds,rp|
g = graph[ta]
graph[ta] = if g.values.any?{|x| !x.nil?}
- g = ds.transform_load(g) if tr
- g = rp[g] if rp
- g
+ rp ? rp.call(g) : g
else
nil
end
View
32 lib/sequel/dataset/sql.rb
@@ -87,9 +87,8 @@ def count
#
# dataset.filter{|o| o.price >= 100}.delete_sql #=>
# "DELETE FROM items WHERE (price >= 100)"
- def delete_sql(opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#delete_sql with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).delete_sql.") unless defarg
- opts = opts ? @opts.merge(opts) : @opts
+ def delete_sql
+ opts = @opts
return static_sql(opts[:sql]) if opts[:sql]
@@ -147,9 +146,8 @@ def exclude(*cond, &block)
#
# DB.select(1).where(DB[:items].exists).sql
# #=> "SELECT 1 WHERE EXISTS (SELECT * FROM items)"
- def exists(opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#exists with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).exists.") unless defarg
- LiteralString.new("EXISTS (#{defarg ? select_sql : select_sql(opts)})")
+ def exists
+ LiteralString.new("EXISTS (#{select_sql})")
end
# Returns a copy of the dataset with the given conditions imposed upon it.
@@ -324,7 +322,6 @@ def insert_sql(*values)
when Hash
values = @opts[:defaults].merge(values) if @opts[:defaults]
values = values.merge(@opts[:overrides]) if @opts[:overrides]
- values = transform_save(values) if @transform
if values.empty?
insert_default_values_sql
else
@@ -683,19 +680,17 @@ def select_more(*columns, &block)
# Formats a SELECT statement
#
# dataset.select_sql # => "SELECT * FROM items"
- def select_sql(opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#select_sql with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).select_sql.") unless defarg
- opts = opts ? @opts.merge(opts) : @opts
+ def select_sql
+ opts = @opts
return static_sql(opts[:sql]) if opts[:sql]
sql = 'SELECT'
- select_clause_order.each{|x| send("select_#{x}_sql", sql, opts)}
+ select_clause_order.each{|x| send(:"select_#{x}_sql", sql, opts)}
sql
end
# Same as select_sql, not aliased directly to make subclassing simpler.
- def sql(opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#select_sql with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).select_sql.") unless defarg
- defarg ? select_sql : select_sql(opts)
+ def sql
+ select_sql
end
# SQL fragment for specifying subscripts (SQL arrays)
@@ -733,9 +728,8 @@ def unordered
#
# Raises an error if the dataset is grouped or includes more
# than one table.
- def update_sql(values = {}, opts = (defarg=true;nil))
- Deprecation.deprecate("Calling Dataset#update_sql with an argument is deprecated and will raise an error in Sequel 3.0. Use dataset.clone(opts).update_sql.") unless defarg
- opts = opts ? @opts.merge(opts) : @opts
+ def update_sql(values = {})
+ opts = @opts
return static_sql(opts[:sql]) if opts[:sql]
@@ -750,7 +744,6 @@ def update_sql(values = {}, opts = (defarg=true;nil))
values = opts[:defaults].merge(values) if opts[:defaults]
values = values.merge(opts[:overrides]) if opts[:overrides]
# get values from hash
- values = transform_save(values) if @transform
values.map do |k, v|
"#{[String, Symbol].any?{|c| k.is_a?(c)} ? quote_identifier(k) : literal(k)} = #{literal(v)}"
end.join(COMMA_SEPARATOR)
@@ -775,7 +768,7 @@ def where(*cond, &block)
end
# Returns a copy of the dataset with the static SQL used. This is useful if you want
- # to keep the same row_proc/transform/graph, but change the SQL used to custom SQL.
+ # to keep the same row_proc/graph, but change the SQL used to custom SQL.
#
# dataset.with_sql('SELECT * FROM foo') # SELECT * FROM foo
def with_sql(sql, *args)
@@ -802,7 +795,6 @@ def to_table_reference(table_alias=nil)
# Internal filter method so it works on either the having or where clauses.
def _filter(clause, *cond, &block)
cond = cond.first if cond.size == 1
- cond = transform_save(cond) if @transform if cond.is_a?(Hash)
cond = filter_expr(cond, &block)
cond = SQL::BooleanExpression.new(:AND, @opts[clause], cond) if @opts[clause]
clone(clause => cond)
View
593 lib/sequel/deprecated.rb
@@ -1,593 +0,0 @@
-%w'bigdecimal/util enumerator yaml'.each do |f|
- require f
-end
-
-module Sequel
- # This module makes it easy to print deprecation warnings with optional backtraces to a given stream.
- # There are a couple of methods you can use to change where the deprecation methods are printed
- # and whether they should include backtraces:
- #
- # Sequel::Deprecation.output = $stderr # print deprecation messages to standard error (default)
- # Sequel::Deprecation.output = File.open('deprecated_calls.txt', 'wb') # use a file instead
- # Sequel::Deprecation.backtraces = false # don't include backtraces
- # Sequel::Deprecation.backtraces = true # include full backtraces
- # Sequel::Deprecation.backtraces = 10 # include 10 backtrace lines (default)
- # Sequel::Deprecation.backtraces = 1 # include 1 backtrace line
- module Deprecation
- extend Metaprogramming
-
- @output = $stderr
- @backtraces = 10
-
- metaattr_accessor :output, :backtraces
-
- # Print the message to the output stream
- def self.deprecate(method, instead=nil)
- message = instead ? "#{method} is deprecated and will be removed in Sequel 3.0. #{instead}." : method
- return unless output
- output.puts(message)
- case backtraces
- when Integer
- b = backtraces
- caller.each do |c|
- b -= 1
- output.puts(c)
- break if b == 0
- end
- when true
- caller.each{|c| output.puts(c)}
- end
- end
- end
-
- require 'deprecated_migration'
-
- def self.open(*args, &block)
- Deprecation.deprecate('Sequel.open', 'Use Sequel.connect')
- Database.connect(*args, &block)
- end
-
- def self.upcase_identifiers=(value)
- Deprecation.deprecate('Sequel.upcase_identifiers=', 'Use Sequel.identifier_input_method = :upcase or nil')
- Database.identifier_input_method = value ? :upcase : nil
- end
-
- def self.use_parse_tree
- Deprecation.deprecate('Sequel.use_parse_tree', 'Sequel has not used ParseTree since 2.2')
- false
- end
-
- def self.use_parse_tree=(val)
- Deprecation.deprecate('Sequel.use_parse_tree=', 'Sequel has not used ParseTree since 2.2')
- raise(Error, 'ParseTree support has been removed from Sequel') if val
- end
-
- class Database
- def self.upcase_identifiers=(value)
- Deprecation.deprecate('Sequel::Database.upcase_identifiers=', 'Use Sequel::Database.identifier_input_method = :upcase or nil')
- self.identifier_input_method = value ? :upcase : nil
- end
-
- def upcase_identifiers=(v)
- Deprecation.deprecate('Sequel::Database#upcase_identifiers=', 'Use Sequel::Database#identifier_input_method = :upcase or nil')
- self.identifier_input_method = v ? :upcase : nil
- end
-
- def upcase_identifiers?
- Deprecation.deprecate('Sequel::Database#upcase_identifiers?', 'Use Sequel::Database#identifier_input_method == :upcase')
- identifier_input_method == :upcase
- end
-
- def >>(*args, &block)
- Deprecation.deprecate('Sequel::Database#>>', 'Use Sequel::Database#fetch')
- fetch(*args, &block)
- end
-
- def query(&block)
- Deprecation.deprecate('Sequel::Database#query', 'require "sequel/extensions/query" first')
- dataset.query(&block)
- end
-
- def logger
- Deprecation.deprecate('Sequel::Database#logger', 'Use Sequel::Database#loggers')
- @loggers.first
- end
-
- def multi_threaded?
- Deprecation.deprecate('Sequel::Database#multi_threaded?', 'Use !database.single_threaded?')
- !@single_threaded
- end
- end
-
- class Dataset
- DATASET_CLASSES = []
- STOCK_TRANSFORMS = {
- :marshal => [
- # for backwards-compatibility we support also non-base64-encoded values.
- proc {|v| Marshal.load(v.unpack('m')[0]) rescue Marshal.load(v)},
- proc {|v| [Marshal.dump(v)].pack('m')}
- ],
- :yaml => [
- proc {|v| YAML.load v if v},
- proc {|v| v.to_yaml}
- ]
- }
-
- def self.dataset_classes
- Deprecation.deprecate('Sequel::Dataset#dataset_classes', 'No replacement is planned')
- DATASET_CLASSES
- end
-
- def self.inherited(c)
- DATASET_CLASSES << c
- end
-
- def upcase_identifiers=(v)
- Deprecation.deprecate('Sequel::Dataset#upcase_identifiers=', 'Use Sequel::Dataset#identifier_input_method = :upcase or nil')
- @identifier_input_method = v ? :upcase : nil
- end
-
- def upcase_identifiers?
- Deprecation.deprecate('Sequel::Dataset#upcase_identifiers?', 'Use Sequel::Dataset#identifier_input_method == :upcase')
- @identifier_input_method == :upcase
- end
-
- def model_classes
- Deprecation.deprecate('Sequel::Dataset#model_classes', 'Sequel::Model datasets no longer set this information')
- @opts[:models]
- end
-
- def polymorphic_key
- Deprecation.deprecate('Sequel::Dataset#polymorphic_key', 'Sequel::Model datasets no longer set this information')
- @opts[:polymorphic_key]
- end
-
- def set_model(key, *args)
- Deprecation.deprecate('Sequel::Dataset#set_model', 'Use Sequel::Dataset#set_row_proc with an appropriate row proc')
- # This code is more verbose then necessary for performance reasons
- case key
- when nil # set_model(nil) => no argument provided, so the dataset is denuded
- @opts.merge!(:naked => true, :models => nil, :polymorphic_key => nil)
- self.row_proc = nil
- when Class
- # isomorphic model
- @opts.merge!(:naked => nil, :models => {nil => key}, :polymorphic_key => nil)
- if key.respond_to?(:load)
- # the class has a values setter method, so we use it
- self.row_proc = proc{|h| key.load(h, *args)}
- else
- # otherwise we just pass the hash to the constructor
- self.row_proc = proc{|h| key.new(h, *args)}
- end
- when Symbol
- # polymorphic model
- hash = args.shift || raise(ArgumentError, "No class hash supplied for polymorphic model")
- @opts.merge!(:naked => true, :models => hash, :polymorphic_key => key)
- if (hash.empty? ? (hash[nil] rescue nil) : hash.values.first).respond_to?(:load)
- # the class has a values setter method, so we use it
- self.row_proc = proc do |h|
- c = hash[h[key]] || hash[nil] || \
- raise(Error, "No matching model class for record (#{polymorphic_key} => #{h[polymorphic_key].inspect})")
- c.load(h, *args)
- end
- else
- # otherwise we just pass the hash to the constructor
- self.row_proc = proc do |h|
- c = hash[h[key]] || hash[nil] || \
- raise(Error, "No matching model class for record (#{polymorphic_key} => #{h[polymorphic_key].inspect})")
- c.new(h, *args)
- end
- end
- else
- raise ArgumentError, "Invalid model specified"
- end
- self
- end
-
- def create_view(name)
- Sequel::Deprecation.deprecate('Sequel::Dataset#create_view', 'Use Sequel::Database#create_view')
- @db.create_view(name, self)
- end
-
- def create_or_replace_view(name)
- Sequel::Deprecation.deprecate('Sequel::Dataset#create_or_replace_view', 'Use Sequel::Database#create_or_replace_view')
- @db.create_or_replace_view(name, self)
- end
-
- def size
- Sequel::Deprecation.deprecate('Sequel::Dataset#size', 'Use Sequel::Dataset#count')
- count
- end
-
- def uniq(*args)
- Sequel::Deprecation.deprecate('Sequel::Dataset#uniq', 'Use Sequel::Dataset#distinct')
- distinct(*args)
- end
-
- def quote_column_ref(name)
- Sequel::Deprecation.deprecate('Sequel::Dataset#quote_column_ref', 'Use Sequel::Dataset#quote_identifier')
- quote_identifier(name)
- end
-
- def symbol_to_column_ref(sym)
- Sequel::Deprecation.deprecate('Sequel::Dataset#symbol_to_column_ref', 'Use Sequel::Dataset#literal')
- literal_symbol(sym)
- end
-
- def paginate(page_no, page_size, record_count=nil)
- Sequel::Deprecation.deprecate('Sequel::Dataset#paginate', 'require "sequel/extensions/pagination" first')
- require "sequel/extensions/pagination"
- raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit]
- paginated = limit(page_size, (page_no - 1) * page_size)
- paginated.extend(Pagination)
- paginated.set_pagination_info(page_no, page_size, record_count || count)
- end
-
- def each_page(page_size, &block)
- Sequel::Deprecation.deprecate('Sequel::Dataset#each_page', 'require "sequel/extensions/pagination" first')
- raise(Error, "You cannot paginate a dataset that already has a limit") if @opts[:limit]
- record_count = count
- total_pages = (record_count / page_size.to_f).ceil
- (1..total_pages).each{|page_no| yield paginate(page_no, page_size, record_count)}
- self
- end
-
- def query(&block)
- Sequel::Deprecation.deprecate('Sequel::Dataset#each_page', 'require "sequel/extensions/query" first')
- require "sequel/extensions/query"
- copy = clone({})
- copy.extend(QueryBlockCopy)
- copy.instance_eval(&block)
- clone(copy.opts)
- end
-
- def print(*cols)
- Sequel::Deprecation.deprecate('Sequel::Dataset#print', 'require "sequel/extensions/pretty_table" first')
- Sequel::PrettyTable.print(naked.all, cols.empty? ? columns : cols)
- end
-
- def transform(t)
- Sequel::Deprecation.deprecate('Sequel::Dataset#transform', 'There is no replacement.')
- @transform = t
- t.each do |k, v|
- case v
- when Array
- if (v.size != 2) || !v.first.is_a?(Proc) && !v.last.is_a?(Proc)
- raise Error::InvalidTransform, "Invalid transform specified"
- end
- else
- unless v = STOCK_TRANSFORMS[v]
- raise Error::InvalidTransform, "Invalid transform specified"
- else
- t[k] = v
- end
- end
- end
- self
- end
-
- def transform_load(r)
- r.inject({}) do |m, kv|
- k, v = *kv
- m[k] = (tt = @transform[k]) ? tt[0][v] : v
- m
- end
- end
-
- def transform_save(r)
- r.inject({}) do |m, kv|
- k, v = *kv
- m[k] = (tt = @transform[k]) ? tt[1][v] : v
- m
- end
- end
- end
-
- module SQL
- module CastMethods
- def cast_as(sql_type)
- Sequel::Deprecation.deprecate('Sequel::SQL::CastMethods#cast_as', 'Use Sequel::SQL::CastMethods#cast')
- cast(sql_type)
- end
- end
-
- class Blob
- def to_blob(*args)
- Sequel::Deprecation.deprecate('Sequel::SQL::Blob#to_blob', 'Use Sequel::SQL::Blob#to_sequel_blob')
- to_sequel_blob(*args)
- end
- end
- end
-
- module PrettyTable
- def self.print(*args)
- Sequel::Deprecation.deprecate('Sequel::PrettyTable#print', 'require "sequel/extensions/pretty_table" first')
- require "sequel/extensions/pretty_table"
- print(*args)
- end
- end
-
- class Error
- class InvalidStatement < Error; end
- class InvalidTransform < Error; end
- class NoExistingFilter < InvalidOperation; end
- end
-end
-
-if RUBY_VERSION < '1.9.0'
- class Hash
- unless method_defined?(:key)
- include(Module.new do
- def key(*args, &block)
- Sequel::Deprecation.deprecate('Hash#key', 'Use Hash#index')
- index(*args, &block)
- end
- end)
- end
- end
-end
-
-module Enumerable
- unless method_defined?(:send_each)
- def send_each(sym, *args)
- Sequel::Deprecation.deprecate('Enumerable#send_each', 'Use Enumerable#each{|x| x.send(...)}')
- each{|i| i.send(sym, *args)}
- end
- end
-end
-
-class Range
- unless method_defined?(:interval)
- include(Module.new do
- def interval
- Sequel::Deprecation.deprecate('Range#interval', 'Use range.first - range.last - (range.exclude_end? ? 1 : 0)')
- last - first - (exclude_end? ? 1 : 0)
- end
- end)
- end
-end
-
-class Array
- unless method_defined?(:extract_options!)
- include(Module.new do
- def extract_options!
- Sequel::Deprecation.deprecate('Array#extract_options!', 'Use array.last.is_a?(Hash) ? array.pop : {}')
- last.is_a?(Hash) ? pop : {}
- end
- end)
- end
-
- def to_sql
- Sequel::Deprecation.deprecate('Array#to_sql', 'It may be a good idea to refactor your implementation so this type of method is not required')
- map {|l| ((m = /^(.*)--/.match(l)) ? m[1] : l).chomp}.join(' '). \
- gsub(/\/\*.*\*\//, '').gsub(/\s+/, ' ').strip
- end
-end
-
-class String
- include(Module.new do
- def split_sql
- Sequel::Deprecation.deprecate('String#split_sql', 'It may be a good idea to refactor your implementation so this type of method is not required')
- to_sql.split(';').map {|s| s.strip}
- end
-
- def to_sql
- Sequel::Deprecation.deprecate('String#to_sql', 'It may be a good idea to refactor your implementation so this type of method is not required')
- split("\n").to_sql
- end
-
- def expr(*args)
- Sequel::Deprecation.deprecate('String#expr', 'Use String#lit')
- lit(*args)
- end
-
- unless String.method_defined?(:to_blob)
- def to_blob(*args)
- Sequel::Deprecation.deprecate('String#to_blob', 'Use String#to_sequel_blob')
- to_sequel_blob(*args)
- end
- end
-
- unless String.method_defined?(:blank?)
- def blank?
- Sequel::Deprecation.deprecate('String#blank?', "require 'sequel/extensions/blank' first")
- strip.empty?
- end
- end
-
- unless String.method_defined?(:to_date)
- def to_date
- Sequel::Deprecation.deprecate('String#to_date', 'You should require "sequel/extensions/string_date_time"')
- begin
- Date.parse(self, Sequel.convert_two_digit_years)
- rescue => e
- raise Sequel::Error::InvalidValue, "Invalid Date value '#{self}' (#{e.message})"
- end
- end
- end
-
- unless String.method_defined?(:to_datetime)
- def to_datetime
- Sequel::Deprecation.deprecate('String#to_datetime', 'You should require "sequel/extensions/string_date_time"')
- begin
- DateTime.parse(self, Sequel.convert_two_digit_years)
- rescue => e
- raise Sequel::Error::InvalidValue, "Invalid DateTime value '#{self}' (#{e.message})"
- end
- end
- end
-
- unless String.method_defined?(:to_sequel_time)
- def to_sequel_time
- Sequel::Deprecation.deprecate('String#to_sequel_time', 'You should require "sequel/extensions/string_date_time"')
- begin
- if Sequel.datetime_class == DateTime
- DateTime.parse(self, Sequel.convert_two_digit_years)
- else
- Sequel.datetime_class.parse(self)
- end
- rescue => e
- raise Sequel::Error::InvalidValue, "Invalid #{Sequel.datetime_class} value '#{self}' (#{e.message})"
- end
- end
- end
-
- unless String.method_defined?(:to_time)
- def to_time
- Sequel::Deprecation.deprecate('String#to_time', 'You should require "sequel/extensions/string_date_time"')
- begin
- Time.parse(self)
- rescue => e
- raise Sequel::Error::InvalidValue, "Invalid Time value '#{self}' (#{e.message})"
- end
- end
- end
- end)
-end
-
-class Symbol
- def |(sub)
- return super unless (Integer === sub) || ((Array === sub) && sub.any?{|x| Integer === x})
- Sequel::Deprecation.deprecate('The use of Symbol#| for SQL array subscripts', 'Use Symbol#sql_subscript')
- Sequel::SQL::Subscript.new(self, Array(sub))
- end
-
- def to_column_ref(ds)
- Sequel::Deprecation.deprecate('Symbol#to_column_ref', 'Use Dataset#literal')
- ds.literal(self)
- end
-end
-
-class Module
- include(Module.new do
- unless Module.method_defined?(:class_def)
- def class_def(name, &block)
- Sequel::Deprecation.deprecate('Object#class_def', "Install the metaid gem")
- class_eval{define_method(name, &block)}
- end
- end
-
- private
-
- unless Module.method_defined?(:class_attr_overridable)
- def class_attr_overridable(*meths)
- Sequel::Deprecation.deprecate('Module#class_attr_overridable', "Copy the method from #{__FILE__} (line #{__LINE__}) if you need it")
- meths.each{|meth| class_eval("def #{meth}; !defined?(@#{meth}) ? (@#{meth} = self.class.#{meth}) : @#{meth} end")}
- attr_writer(*meths)
- end
- end
-
- unless Module.method_defined?(:class_attr_reader)
- def class_attr_reader(*meths)
- Sequel::Deprecation.deprecate('Module#class_attr_reader', "Copy the method from #{__FILE__} (line #{__LINE__}) if you need it")
- meths.each{|meth| define_method(meth){self.class.send(meth)}}
- end
- end
-
- unless Module.method_defined?(:metaalias)
- def metaalias(to, from)
- Sequel::Deprecation.deprecate('Module#metaalias', "Copy the method from #{__FILE__} (line #{__LINE__}) if you need it")
- meta_eval{alias_method to, from}
- end
- end
-
- unless Module.method_defined?(:metaattr_accessor)
- def metaattr_accessor(*meths)
- Sequel::Deprecation.deprecate('Module#metaattr_accessor', "Copy the method from #{__FILE__} (line #{__LINE__}) if you need it")
- meta_eval{attr_accessor(*meths)}
- end
- end
-
- unless Module.method_defined?(:metaattr_reader)
- def metaattr_reader(*meths)
- Sequel::Deprecation.deprecate('Module#metaattr_reader', "Copy the method from #{__FILE__} (line #{__LINE__}) if you need it")
- meta_eval{attr_reader(*meths)}
- end
- end
- end)
-end
-
-class FalseClass
- unless method_defined?(:blank?)
- include(Module.new do
- def blank?
- Sequel::Deprecation.deprecate('FalseClass#blank?', "require 'sequel/extensions/blank' first")
- true
- end
- end)
- end
-end
-
-class NilClass
- unless method_defined?(:blank?)
- include(Module.new do
- def blank?
- Sequel::Deprecation.deprecate('NilClass#blank?', "require 'sequel/extensions/blank' first")
- true
- end
- end)
- end
-end
-
-class Numeric
- unless method_defined?(:blank?)
- include(Module.new do
- def blank?
- Sequel::Deprecation.deprecate('Numeric#blank?', "require 'sequel/extensions/blank' first")
- false
- end
- end)
- end
-end
-
-class TrueClass
- unless method_defined?(:blank?)
- include(Module.new do
- def blank?
- Sequel::Deprecation.deprecate('FalseClass#blank?', "require 'sequel/extensions/blank' first")
- false
- end
- end)
- end
-end
-
-class Object
- include(Module.new do
- unless Object.method_defined?(:blank?)
- def blank?
- Sequel::Deprecation.deprecate('FalseClass#blank?', "require 'sequel/extensions/blank' first")
- respond_to?(:empty?) && empty?
- end
- end
-
- unless Object.method_defined?(:is_one_of?)
- def is_one_of?(*classes)
- Sequel::Deprecation.deprecate('Object#is_one_of?', "Use classes.any?{|c| object.is_a?(c)}")
- classes.any?{|c| is_a?(c)}
- end
- end
-
- unless Object.method_defined?(:meta_def)
- def meta_def(name, &block)
- Sequel::Deprecation.deprecate('Object#meta_def', "Install the metaid gem")
- meta_eval{define_method(name, &block)}
- end
- end
-
- unless Object.method_defined?(:meta_eval)
- def meta_eval(&block)
- Sequel::Deprecation.deprecate('Object#meta_eval', "Install the metaid gem")
- metaclass.instance_eval(&block)
- end
- end
-
- unless Object.method_defined?(:metaclass)
- def metaclass
- Sequel::Deprecation.deprecate('Object#metaclass', "Install the metaid gem")
- class << self
- self
- end
- end
- end
- end)
-end
View
91 lib/sequel/deprecated_migration.rb
@@ -1,91 +0,0 @@
-module Sequel
- class Migration
- def initialize(db)
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- @db = db
- end
-
- def self.apply(db, direction)
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- apply(db, direction)
- end
-
- def self.descendants
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- @descendants ||= []
- end
-
- def self.inherited(base)
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- descendants << base
- end
-
- def down
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- end
-
- def method_missing(method_sym, *args, &block)
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- @db.send(method_sym, *args, &block)
- end
-
- def up
- Deprecation.deprecate('Sequel::Migration', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- end
- end
-
- module Migrator
- def self.apply(db, directory, target = nil, current = nil)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- apply(db, directory, target, current)
- end
-
- def self.get_current_migration_version(db)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- r = schema_info_dataset(db).first
- r ? r[:version] : 0
- end
-
- def self.latest_migration_version(directory)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- l = migration_files(directory).last
- l ? File.basename(l).to_i : nil
- end
-
- def self.migration_classes(directory, target, current, direction)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- migration_classes(directory, target, current, direction)
- end
-
- def self.migration_files(directory, range = nil)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- migration_files(directory, range)
- end
-
- def self.schema_info_dataset(db)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- db.create_table(:schema_info) {integer :version} unless db.table_exists?(:schema_info)
- db[:schema_info]
- end
-
- def self.set_current_migration_version(db, version)
- Deprecation.deprecate('Sequel::Migrator', "require 'sequel/extensions/migration' first")
- require 'sequel/extensions/migration'
- dataset = schema_info_dataset(db)
- dataset.send(dataset.first ? :update : :<<, :version => version)
- end
- end
-end
View
5 lib/sequel/extensions/inflector.rb
@@ -32,7 +32,6 @@ class << self
# clear :all
# clear :plurals
def self.clear(scope = :all)
- Sequel::Inflections.clear(scope)
case scope
when :all
@plurals, @singulars, @uncountables = [], [], []
@@ -48,7 +47,6 @@ def self.clear(scope = :all)
# irregular 'octopus', 'octopi'
# irregular 'person', 'people'
def self.irregular(singular, plural)
- Sequel::Inflections.irregular(singular, plural)
plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
end
@@ -59,7 +57,6 @@ def self.irregular(singular, plural)
# Example:
# plural(/(x|ch|ss|sh)$/i, '\1es')
def self.plural(rule, replacement)
- Sequel::Inflections.plural(rule, replacement)
@plurals.insert(0, [rule, replacement])
end
@@ -69,7 +66,6 @@ def self.plural(rule, replacement)
# Example:
# singular(/([^aeiouy]|qu)ies$/i, '\1y')
def self.singular(rule, replacement)
- Sequel::Inflections.singular(rule, replacement)
@singulars.insert(0, [rule, replacement])
end
@@ -80,7 +76,6 @@ def self.singular(rule, replacement)
# uncountable "money", "information"
# uncountable %w( money information rice )
def self.uncountable(*words)
- Sequel::Inflections.uncountable(*words)
(@uncountables << words).flatten!
end
View
3  lib/sequel/model.rb
@@ -45,7 +45,7 @@ class Model
last left_outer_join limit map multi_insert naked order order_by
order_more paginate print query range reverse_order right_outer_join
select select_all select_more server set set_graph_aliases
- single_value to_csv to_hash transform union unfiltered unordered
+ single_value to_csv to_hash union unfiltered unordered
update where with_sql'.map{|x| x.to_sym}
# Class instance variables to set to nil when a subclass is created, for -w compliance
@@ -106,5 +106,4 @@ class Model
require 'associations', 'model'
Model.plugin Model::Associations
end
- require 'deprecated', 'model'
end
View
10 lib/sequel/model/base.rb
@@ -285,7 +285,6 @@ def set_dataset(ds, opts={})
raise(Error, "Model.set_dataset takes a Symbol or a Sequel::Dataset")
end
@dataset.row_proc = Proc.new{|r| load(r)}
- @dataset.transform(@transform) if @transform
if inherited
@simple_table = superclass.simple_table
@columns = @dataset.columns rescue nil
@@ -438,8 +437,6 @@ def overridable_methods_module
def set_columns(new_columns)
@columns = new_columns
def_column_accessor(*new_columns) if new_columns
- # Deprecation.deprecated
- @str_columns = nil
@columns
end
@@ -837,16 +834,12 @@ def save_failure(type)
# Set the columns, filtered by the only and except arrays.
def set_restricted(hash, only, except)
- columns_not_set = [nil, false, "", [], {}].include?(model.instance_variable_get(:@columns))
meths = setter_methods(only, except)
strict = strict_param_setting
hash.each do |k,v|
m = "#{k}="
if meths.include?(m)
send(m, v)
- elsif columns_not_set && (Symbol === k)
- Deprecation.deprecate('Calling Model#set_restricted for a column without a setter method when the model class does not have any columns', 'Use Model#[] for these columns')
- self[k] = v
elsif strict
raise Error, "method #{m} doesn't exist or access is restricted to it"
end
@@ -887,8 +880,7 @@ def setter_methods(only, except)
# typecast_value method, so database adapters can override/augment the handling
# for database specific column types.
def typecast_value(column, value)
- # Deprecation.deprecate : Remove model.serialized call
- return value unless typecast_on_assignment && db_schema && (col_schema = db_schema[column]) && !model.serialized?(column)
+ return value unless typecast_on_assignment && db_schema && (col_schema = db_schema[column])
value = nil if value == '' and typecast_empty_string_to_nil and col_schema[:type] and ![:string, :blob].include?(col_schema[:type])
raise(InvalidValue, "nil/NULL is not allowed for the #{column} column") if raise_on_typecast_failure && value.nil? && (col_schema[:allow_null] == false)
begin
View
204 lib/sequel/model/deprecated.rb
@@ -1,204 +0,0 @@
-Sequel.require %w'deprecated_hooks deprecated_validations deprecated_inflector', 'model'
-
-module Sequel
- class Model
- module Validation
- Errors = Model::Errors
- end
- module ClassMethods
- {:size=>:count, :uniq=>:distinct}.each do |o, n|
- class_eval "def #{o}(*args, &block); Deprecation.deprecate('Sequel::Model.#{o}', 'Use Sequel::Model.dataset.#{n}'); dataset.#{n}(*args, &block); end"
- end
-
- def is(*args, &block)
- Deprecation.deprecate('Sequel::Model.is', 'Use Sequel::Model.plugin')
- plugin(*args, &block)
- end
-
- def is_a(*args, &block)
- Deprecation.deprecate('Sequel::Model.is_a', 'Use Sequel::Model.plugin')
- plugin(*args, &block)
- end
-
- def delete_all
- Deprecation.deprecate('Sequel::Model.delete_all', 'Use Sequel::Model.delete')
- dataset.delete
- end
-
- def destroy_all
- Deprecation.deprecate('Sequel::Model.destroy_all', 'Use Sequel::Model.destroy')
- dataset.destroy
- end
-
- def str_columns
- Deprecation.deprecate('Sequel::Model.str_columns', 'Use model.columns.map{|x| x.to_s}')
- @str_columns ||= columns.map{|c| c.to_s.freeze}
- end
-
- def set_sti_key(key)
- Deprecation.deprecate('Sequel::Model.set_sti_key', 'Use Model.plugin(:single_table_inheritance, key)')
- plugin :single_table_inheritance, key
- end
-
- def sti_key
- Deprecation.deprecate('Sequel::Model.sti_key', 'Use Model.plugin(:single_table_inheritance, key) first')
- @sti_key
- end
-
- def sti_dataset
- Deprecation.deprecate('Sequel::Model.sti_dataset', 'Use Model.plugin(:single_table_inheritance, key) first')
- @sti_dataset
- end
-
- def set_cache_ttl(ttl)
- Deprecation.deprecate('Sequel::Model.set_cache_ttl', 'Use Model.plugin(:caching, store, opts) first')
- @cache_ttl = ttl
- end
-
- def set_cache(store, opts = {})
- Deprecation.deprecate('Sequel::Model.set_cache', 'Use Model.plugin(:caching, store, opts)')
- plugin :caching, store, opts
- end
-
- # Creates table, using the column information from set_schema.
- def create_table
- Deprecation.deprecate('Sequel::Model.create_table', 'Use Model.plugin(:schema) first')
- db.create_table(table_name, :generator=>@schema)
- @db_schema = get_db_schema(true)
- columns
- end
-
- # Drops the table if it exists and then runs create_table. Should probably
- # not be used except in testing.
- def create_table!
- Deprecation.deprecate('Sequel::Model.create_table!', 'Use Model.plugin(:schema) first')
- drop_table rescue nil
- create_table
- end
-
- # Drops table.
- def drop_table
- Deprecation.deprecate('Sequel::Model.drop_table', 'Use Model.plugin(:schema) first')
- db.drop_table(table_name)
- end
-
- # Returns table schema created with set_schema for direct descendant of Model.
- # Does not retreive schema information from the database, see db_schema if you
- # want that.
- def schema
- Deprecation.deprecate('Sequel::Model.schema', 'Use Model.plugin(:schema) first')
- @schema || (superclass.schema unless superclass == Model)
- end
-
- # Defines a table schema (see Schema::Generator for more information).
- #
- # This is only needed if you want to use the create_table/create_table! methods.
- # Will also set the dataset if you provide a name, as well as setting
- # the primary key if you defined one in the passed block.
- #
- # In general, it is a better idea to use migrations for production code, as
- # migrations allow changes to existing schema. set_schema is mostly useful for
- # test code or simple examples.
- def set_schema(name = nil, &block)
- Deprecation.deprecate('Sequel::Model.set_schema', 'Use Model.plugin(:schema) first')
- set_dataset(db[name]) if name
- @schema = Sequel::Schema::Generator.new(db, &block)
- set_primary_key(@schema.primary_key_name) if @schema.primary_key_name
- end
-
- # Returns true if table exists, false otherwise.
- def table_exists?
- Deprecation.deprecate('Sequel::Model.table_exists?', 'Use Model.plugin(:schema) first')
- db.table_exists?(table_name)
- end
-
- def serialize(*columns)
- Deprecation.deprecate('Sequel::Model.serialize', 'A implementation that doesn\'t use dataset transforms can be added via plugin(:serialization, (:marshal||:yaml), column1, column2)')
- format = extract_options!(columns)[:format] || :yaml
- @transform = columns.inject({}) do |m, c|
- m[c] = format
- m
- end
- @dataset.transform(@transform) if @dataset
- end
-
- def serialized?(column)
- @transform ? @transform.include?(column) : false
- end
- end
-
- module InstanceMethods
- def dataset
- Deprecation.deprecate('Sequel::Model#dataset', 'Use model_object.model.dataset')
- model.dataset
- end
-
- def save!(*args)
- Deprecation.deprecate('Sequel::Model#save!', 'Use model_object.save(..., :validate=>false)')
- opts = args.last.is_a?(Hash) ? args.pop : {}
- args.push(opts.merge(:validate=>false))
- save(*args)
- end
-
- def str_columns
- Deprecation.deprecate('Sequel::Model#str_columns', 'Use model_object.columns.map{|x| x.to_s}')
- model.str_columns
- end
-
- def set_with_params(hash)
- Deprecation.deprecate('Sequel::Model#set_with_params', 'Use Sequel::Model#set')
- set_restricted(hash, nil, nil)
- end
-
- def update_with_params(hash)
- Deprecation.deprecate('Sequel::Model#update_with_params', 'Use Sequel::Model#update')
- update_restricted(hash, nil, nil)
- end
-
- def set_values(values)
- Deprecation.deprecate('Sequel::Model#set_values', 'Use Sequel::Model#set')
- s = str_columns
- vals = values.inject({}) do |m, kv|
- k, v = kv
- k = case k
- when Symbol
- k
- when String
- raise(Error, "all string keys must be a valid columns") unless s.include?(k)
- k.to_sym
- else
- raise(Error, "Only symbols and strings allows as keys")
- end
- m[k] = v
- m
- end
- vals.each {|k, v| @values[k] = v}
- vals
- end
-
- def update_values(values)
- Deprecation.deprecate('Sequel::Model#update_values', 'Use Sequel::Model#update or model_object.this.update')
- this.update(set_values(values))
- end
- end
-
- if defined?(Associations::ClassMethods)
- module Associations::ClassMethods
- def belongs_to(*args, &block)
- Deprecation.deprecate('Sequel::Model.belongs_to', 'Use Sequel::Model.many_to_one')
- many_to_one(*args, &block)
- end
-
- def has_many(*args, &block)
- Deprecation.deprecate('Sequel::Model.has_many', 'Use Sequel::Model.one_to_many')
- one_to_many(*args, &block)
- end
-
- def has_and_belongs_to_many(*args, &block)
- Deprecation.deprecate('Sequel::Model.has_and_belongs_to_many', 'Use Sequel::Model.many_to_many')
- many_to_many(*args, &block)
- end
- end
- end
- end
-end
View
103 lib/sequel/model/deprecated_hooks.rb
@@ -1,103 +0,0 @@
-module Sequel
- module Plugins
- module DeprecatedHookClassMethods
- def self.apply(model)
- hooks = model.instance_variable_set(:@hooks, {})
- Model::HOOKS.each{|h| hooks[h] = []}
- end
-
- module ClassMethods
- Model::HOOKS.each{|h| class_eval("def #{h}(method = nil, &block); Deprecation.deprecate('Sequel::Model.#{h}', 'Use Model.plugin :hook_class_methods'); add_hook(:#{h}, method, &block) end", __FILE__, __LINE__)}
-
- # This adds a new hook type. It will define both a class
- # method that you can use to add hooks, as well as an instance method
- # that you can use to call all hooks of that type. The class method
- # can be called with a symbol or a block or both. If a block is given and
- # and symbol is not, it adds the hook block to the hook type. If a block
- # and symbol are both given, it replaces the hook block associated with
- # that symbol for a given hook type, or adds it if there is no hook block
- # with that symbol for that hook type. If no block is given, it assumes
- # the symbol specifies an instance method to call and adds it to the hook
- # type.
- #
- # If any hook block returns false, the instance method will return false
- # immediately without running the rest of the hooks of that type.
- #
- # It is recommended that you always provide a symbol to this method,
- # for descriptive purposes. It's only necessary to do so when you
- # are using a system that reloads code.
- #
- # Example of usage:
- #
- # class MyModel
- # define_hook :before_move_to
- # before_move_to(:check_move_allowed){|o| o.allow_move?}
- # def move_to(there)
- # return if before_move_to == false
- # # move MyModel object to there
- # end
- # end
- def add_hook_type(*hooks)
- Deprecation.deprecate('Sequel::Model.add_hook_type', 'Use Model.plugin :hook_class_methods')
- hooks.each do |hook|
- @hooks[hook] = []
- instance_eval("def #{hook}(method = nil, &block); add_hook(:#{hook}, method, &block) end", __FILE__, __LINE__)
- class_eval("def #{hook}; run_hooks(:#{hook}); end", __FILE__, __LINE__)
- end
- end
-
- # Returns true if there are any hook blocks for the given hook.
- def has_hooks?(hook)
- !@hooks[hook].empty?
- end
-
- # Yield every block related to the given hook.
- def hook_blocks(hook)
- @hooks[hook].each{|k,v| yield v}
- end
-
- def inherited(subclass)
- super
- hooks = subclass.instance_variable_set(:@hooks, {})
- instance_variable_get(:@hooks).each{|k,v| hooks[k] = v.dup}
- end
-
- private
-
- # Add a hook block to the list of hook methods.
- # If a non-nil tag is given and it already is in the list of hooks,
- # replace it with the new block.
- def add_hook(hook, tag, &block)
- unless block
- (raise Error, 'No hook method specified') unless tag
- block = proc {send tag}
- end
- h = @hooks[hook]
- if tag && (old = h.find{|x| x[0] == tag})
- old[1] = block
- else
- if hook.to_s =~ /^before/
- h.unshift([tag,block])
- else
- h << [tag, block]
- end
- end
- end
- end
-
- module InstanceMethods
- Model::HOOKS.each{|h| class_eval("def #{h}; run_hooks(:#{h}); end", __FILE__, __LINE__)}
-
- private
-
- # Runs all hook blocks of given hook type on this object.
- # Stops running hook blocks and returns false if any hook block returns false.
- def run_hooks(hook)
- model.hook_blocks(hook){|block| return false if instance_eval(&block) == false}
- end
- end
- end
- end
-
- Model.plugin :deprecated_hook_class_methods
-end
View
335 lib/sequel/model/deprecated_inflector.rb
@@ -1,335 +0,0 @@
-# Add inflection methods to String, which allows the easy transformation of
-# words from singular to plural,class names to table names, modularized class
-# names to ones without, and class names to foreign keys.
-
-class String
- # This module acts as a singleton returned/yielded by String.inflections,
- # which is used to override or specify additional inflection rules. Examples: