Skip to content

Instantly share code, notes, and snippets.

@lkfken
Created March 28, 2017 23:36
Show Gist options
  • Save lkfken/8dfb323597e71349d41f9eee564122d5 to your computer and use it in GitHub Desktop.
Save lkfken/8dfb323597e71349d41f9eee564122d5 to your computer and use it in GitHub Desktop.
Sequel: add modulus support
ds_1 = People.select(:birth).select_append{year(:birth).as(:year)}
ds_1.first ##<Member @values={:birth=>1980-09-15 00:00:00 -0700, :year=>1980}>
ds_2 = People.select(:birth).select_append{(year(:birth) % 100 ).as(:year)}
# ds_2.first
# NoMethodError: undefined method `%' for #<Sequel::SQL::Function @name=>:year, @opts=>{}, @args=>[:birth]>
# Mostly because it is less common. It's defined in BitwiseMethods, which is only included in NumericExpression by default.
# Some of the BitwiseMethods overlap with the BooleanMethods that are included in GenericExpression.
# Not all databases support modulus for all numeric types. For example, SQLite doesn't appear to support modulus
# for floating point numbers, always returing NULL. The reason it's defined in BitwiseMethods is it is mostly useful
# for integers (just like the bitwise operators), not for other numeric types.
# If you want, you can define the % method in NumericMethods if you want it to be available for most expression objects:
# Sequel::SQL::NumericMethods.send(:define_method, :%, Sequel::SQL::BitwiseMethods.instance_method(:%))
# Note that % is already defined for Sequel::LiteralString, which includes NumericMethods but not BitwiseMethods,
# so defining % in NumericExpression can affect backwards compatibility.
Sequel::SQL::NumericMethods.send(:define_method, :%, Sequel::SQL::BitwiseMethods.instance_method(:%))
ds_2.first
# <Member @values={:birth=>1980-09-15 00:00:00 -0700, :year=>80}>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment