diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..3c04d288 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,36 @@ +require: + - rubocop-performance + +inherit_gem: + rubocop-shopify: rubocop.yml + +AllCops: + Exclude: + - 'spec/**/*' + SuggestExtensions: false + +Style/MethodCallWithoutArgsParentheses: + Enabled: false + +Style/StringLiterals: + Enabled: false + +Layout/EmptyLineAfterGuardClause: + Enabled: false + +Layout/LineLength: + Max: 120 + AllowedPatterns: + - '^\s*#' + +Style/ClassVars: + Enabled: false + +Style/ClassMethodsDefinitions: + Enabled: false + +Naming/FileName: + Enabled: false + +Style/SpecialGlobalVars: + Enabled: false diff --git a/Gemfile b/Gemfile index 1adeb250..de6e69ba 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,10 @@ # frozen_string_literal: true + source "https://rubygems.org" gem "pry-byebug", require: false -gem 'rubocop', require: false +gem "rubocop", require: false +gem "rubocop-shopify", ">=2.8.0", require: false +gem "rubocop-performance", require: false gemspec diff --git a/Gemfile.lock b/Gemfile.lock index 38c464f1..4e229edd 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -223,6 +223,11 @@ GEM unicode-display_width (>= 2.4.0, < 3.0) rubocop-ast (1.32.3) parser (>= 3.3.1.0) + rubocop-performance (1.22.1) + rubocop (>= 1.48.1, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-shopify (2.15.1) + rubocop (~> 1.51) ruby-progressbar (1.13.0) securerandom (0.3.1) simplecov (0.22.0) @@ -265,6 +270,8 @@ DEPENDENCIES rails (~> 7.2) rspec (~> 3.2) rubocop + rubocop-performance + rubocop-shopify (>= 2.8.0) shopify-money! simplecov sqlite3 diff --git a/Rakefile b/Rakefile index 3b47c3ca..7b4af79c 100644 --- a/Rakefile +++ b/Rakefile @@ -15,7 +15,7 @@ begin rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts "Run `bundle install` to install missing gems" - exit e.status_code + exit(e.status_code) end require 'rake' @@ -30,7 +30,7 @@ RSpec::Core::RakeTask.new(:rcov) do |spec| spec.rcov = true end -task :default => :spec +task default: :spec require 'rake/task' RDoc::Task.new do |rdoc| diff --git a/lib/money.rb b/lib/money.rb index 42ee07a7..1c4c129b 100644 --- a/lib/money.rb +++ b/lib/money.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require_relative 'money/version' require_relative 'money/parser/fuzzy' require_relative 'money/helpers' diff --git a/lib/money/allocator.rb b/lib/money/allocator.rb index 00d84ba9..2255a513 100644 --- a/lib/money/allocator.rb +++ b/lib/money/allocator.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require 'delegate' class Money @@ -107,7 +108,7 @@ def allocate(splits, strategy = :roundrobin) # Money.new(100).allocate_max_amounts([Money.new(5), Money.new(2)]) # #=> [Money.new(5), Money.new(2)] def allocate_max_amounts(maximums) - allocation_currency = extract_currency(maximums + [self.__getobj__]) + allocation_currency = extract_currency(maximums + [__getobj__]) maximums = maximums.map { |max| max.to_money(allocation_currency) } maximums_total = maximums.reduce(Money.new(0, allocation_currency), :+) @@ -116,16 +117,16 @@ def allocate_max_amounts(maximums) Money.rational(max_amount, maximums_total) end - total_allocatable = [maximums_total.subunits, self.subunits].min + total_allocatable = [maximums_total.subunits, subunits].min subunits_amounts, left_over = amounts_from_splits(1, splits, total_allocatable) subunits_amounts.map! { |amount| amount[:whole_subunits] } subunits_amounts.each_with_index do |amount, index| - break unless left_over > 0 + break if left_over <= 0 max_amount = maximums[index].value * allocation_currency.subunit_to_unit - next unless amount < max_amount + next if amount >= max_amount left_over -= 1 subunits_amounts[index] += 1 @@ -137,9 +138,12 @@ def allocate_max_amounts(maximums) private def extract_currency(money_array) - currencies = money_array.lazy.select { |money| money.is_a?(Money) }.reject(&:no_currency?).map(&:currency).to_a.uniq + currencies = money_array.lazy.select do |money| + money.is_a?(Money) + end.reject(&:no_currency?).map(&:currency).to_a.uniq if currencies.size > 1 - raise ArgumentError, "operation not permitted for Money objects with different currencies #{currencies.join(', ')}" + raise ArgumentError, + "operation not permitted for Money objects with different currencies #{currencies.join(", ")}" end currencies.first || NULL_CURRENCY end @@ -154,8 +158,8 @@ def amounts_from_splits(allocations, splits, subunits_to_split = subunits) fractional_subunits = (subunits_to_split * ratio / allocations.to_r).to_f - whole_subunits left_over -= whole_subunits { - :whole_subunits => whole_subunits, - :fractional_subunits => fractional_subunits + whole_subunits: whole_subunits, + fractional_subunits: fractional_subunits, } end @@ -172,7 +176,7 @@ def all_rational?(splits) # the next whole number. Similarly, given the input [9.1, 5.5, 3.9] the correct ranking is *still* 2, 1, 0. This # is because 3.9 is nearer to 4 than 9.1 is to 10. def rank_by_nearest(amounts) - amounts.each_with_index.sort_by{ |amount, i| 1 - amount[:fractional_subunits] }.map(&:last) + amounts.each_with_index.sort_by { |amount, _i| 1 - amount[:fractional_subunits] }.map(&:last) end end end diff --git a/lib/money/core_extensions.rb b/lib/money/core_extensions.rb index 09181d39..3d315894 100644 --- a/lib/money/core_extensions.rb +++ b/lib/money/core_extensions.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # Allows Writing of 100.to_money for +Numeric+ types # 100.to_money => # # 100.37.to_money => # @@ -25,7 +26,7 @@ def to_money(currency = nil) return Money.new(self, currency) end - return Money.new(0, currency) if self.empty? + return Money.new(0, currency) if empty? Money::Parser::Fuzzy.parse(self, currency).tap do |money| old_value = money.value diff --git a/lib/money/currency.rb b/lib/money/currency.rb index 0604f329..c2be6ffa 100644 --- a/lib/money/currency.rb +++ b/lib/money/currency.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require "money/currency/loader" class Money @@ -27,8 +28,16 @@ def currencies end end - attr_reader :iso_code, :iso_numeric, :name, :smallest_denomination, :subunit_symbol, - :subunit_to_unit, :minor_units, :symbol, :disambiguate_symbol, :decimal_mark + attr_reader :iso_code, + :iso_numeric, + :name, + :smallest_denomination, + :subunit_symbol, + :subunit_to_unit, + :minor_units, + :symbol, + :disambiguate_symbol, + :decimal_mark def initialize(currency_iso) data = self.class.currencies[currency_iso] @@ -51,7 +60,7 @@ def eql?(other) end def hash - [ self.class, iso_code ].hash + [self.class, iso_code].hash end def compatible?(other) diff --git a/lib/money/currency/loader.rb b/lib/money/currency/loader.rb index 4109ad1c..3756e47c 100644 --- a/lib/money/currency/loader.rb +++ b/lib/money/currency/loader.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require 'yaml' class Money @@ -9,9 +10,9 @@ def load_currencies currency_data_path = File.expand_path("../../../../config", __FILE__) currencies = {} - currencies.merge! YAML.load_file("#{currency_data_path}/currency_historic.yml") - currencies.merge! YAML.load_file("#{currency_data_path}/currency_non_iso.yml") - currencies.merge! YAML.load_file("#{currency_data_path}/currency_iso.yml") + currencies.merge!(YAML.load_file("#{currency_data_path}/currency_historic.yml")) + currencies.merge!(YAML.load_file("#{currency_data_path}/currency_non_iso.yml")) + currencies.merge!(YAML.load_file("#{currency_data_path}/currency_iso.yml")) deep_deduplicate!(currencies) end diff --git a/lib/money/deprecations.rb b/lib/money/deprecations.rb index 9b4c2530..07b47df3 100644 --- a/lib/money/deprecations.rb +++ b/lib/money/deprecations.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + Money.class_eval do ACTIVE_SUPPORT_DEFINED = defined?(ActiveSupport) diff --git a/lib/money/errors.rb b/lib/money/errors.rb index e9dc5901..219d8e03 100644 --- a/lib/money/errors.rb +++ b/lib/money/errors.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + class Money class Error < StandardError end diff --git a/lib/money/helpers.rb b/lib/money/helpers.rb index b0f2b90d..9a71df74 100644 --- a/lib/money/helpers.rb +++ b/lib/money/helpers.rb @@ -1,9 +1,10 @@ # frozen_string_literal: true + require 'bigdecimal' class Money module Helpers - module_function + extend self DECIMAL_ZERO = BigDecimal(0).freeze MAX_DECIMAL = 21 diff --git a/lib/money/money.rb b/lib/money/money.rb index 9d156bae..fb237cfd 100644 --- a/lib/money/money.rb +++ b/lib/money/money.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require 'forwardable' require 'json' @@ -9,6 +10,7 @@ class Money NULL_CURRENCY = NullCurrency.new.freeze attr_reader :value, :currency + def_delegators :@value, :zero?, :nonzero?, :positive?, :negative?, :to_i, :to_f, :hash class ReverseOperationProxy @@ -38,6 +40,7 @@ def *(other) class << self extend Forwardable attr_accessor :config + def_delegators :@config, :default_currency, :default_currency= def configure @@ -105,13 +108,11 @@ def current_currency=(currency) # I18n.with_locale and ActiveSupport's Time.use_zone. This won't affect # instances being created with explicitly set currency. def with_currency(new_currency) - begin - old_currency = Money.current_currency - Money.current_currency = new_currency - yield - ensure - Money.current_currency = old_currency - end + old_currency = Money.current_currency + Money.current_currency = new_currency + yield + ensure + Money.current_currency = old_currency end private @@ -127,10 +128,12 @@ def new_from_money(amount, currency) return amount end - msg = "Money.new(Money.new(amount, #{amount.currency}), #{currency}) is changing the currency of an existing money object" + msg = "Money.new(Money.new(amount, #{amount.currency}), #{currency}) " \ + "is changing the currency of an existing money object" + if Money.config.legacy_deprecations Money.deprecate("#{msg}. A Money::IncompatibleCurrencyError will raise in the next major release") - return Money.new(amount.value, currency) + Money.new(amount.value, currency) else raise Money::IncompatibleCurrencyError, msg end @@ -195,19 +198,19 @@ def -(other) end end - def *(numeric) - raise ArgumentError, "Money objects can only be multiplied by a Numeric" unless numeric.is_a?(Numeric) + def *(other) + raise ArgumentError, "Money objects can only be multiplied by a Numeric" unless other.is_a?(Numeric) - return self if numeric == 1 - Money.new(value.to_r * numeric, currency) + return self if other == 1 + Money.new(value.to_r * other, currency) end - def /(numeric) + def /(other) raise "[Money] Dividing money objects can lose pennies. Use #split instead" end def inspect - "#<#{self.class} value:#{self} currency:#{self.currency}>" + "#<#{self.class} value:#{self} currency:#{currency}>" end def ==(other) @@ -239,8 +242,10 @@ def to_money(new_currency = nil) return Money.new(value, new_currency) end - ensure_compatible_currency(Helpers.value_to_currency(new_currency), - "to_money is attempting to change currency of an existing money object from #{currency} to #{new_currency}") + ensure_compatible_currency( + Helpers.value_to_currency(new_currency), + "to_money is attempting to change currency of an existing money object from #{currency} to #{new_currency}", + ) self end @@ -261,7 +266,7 @@ def to_fs(style = nil) rounded_value = value.round(units) if units == 0 - sprintf("%d", rounded_value) + format("%d", rounded_value) else formatted = rounded_value.to_s("F") decimal_digits = formatted.size - formatted.index(".") - 1 @@ -303,7 +308,7 @@ def floor Money.new(floor, currency) end - def round(ndigits=0) + def round(ndigits = 0) round = value.round(ndigits) return self if round == value Money.new(round, currency) @@ -364,13 +369,13 @@ def calculate_splits(num) def clamp(min, max) raise ArgumentError, 'min cannot be greater than max' if min > max - clamped_value = min if self.value < min - clamped_value = max if self.value > max + clamped_value = min if value < min + clamped_value = max if value > max if clamped_value.nil? self else - Money.new(clamped_value, self.currency) + Money.new(clamped_value, currency) end end @@ -379,8 +384,10 @@ def clamp(min, max) def arithmetic(other) case other when Money - ensure_compatible_currency(other.currency, - "mathematical operation not permitted for Money objects with different currencies #{other.currency} and #{currency}.") + desc = "mathematical operation not permitted for Money objects with different currencies " \ + "#{other.currency} and #{currency}." + + ensure_compatible_currency(other.currency, desc) yield(other) when Numeric, String diff --git a/lib/money/null_currency.rb b/lib/money/null_currency.rb index 2e3fb88f..4c80b0a1 100644 --- a/lib/money/null_currency.rb +++ b/lib/money/null_currency.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + class Money # A placeholder currency for instances where no actual currency is available, # as defined by ISO4217. You should rarely, if ever, need to use this @@ -32,9 +33,16 @@ class Money # #=> # # class NullCurrency - - attr_reader :iso_code, :iso_numeric, :name, :smallest_denomination, :subunit_symbol, - :subunit_to_unit, :minor_units, :symbol, :disambiguate_symbol, :decimal_mark + attr_reader :iso_code, + :iso_numeric, + :name, + :smallest_denomination, + :subunit_symbol, + :subunit_to_unit, + :minor_units, + :symbol, + :disambiguate_symbol, + :decimal_mark def initialize @symbol = '$' diff --git a/lib/money/parser/accounting.rb b/lib/money/parser/accounting.rb index 4e5e41ec..f79e4b4d 100644 --- a/lib/money/parser/accounting.rb +++ b/lib/money/parser/accounting.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + class Money module Parser class Accounting < Fuzzy diff --git a/lib/money/parser/fuzzy.rb b/lib/money/parser/fuzzy.rb index 1bb9ce58..1d63e1d4 100644 --- a/lib/money/parser/fuzzy.rb +++ b/lib/money/parser/fuzzy.rb @@ -1,43 +1,44 @@ # frozen_string_literal: true + class Money module Parser class Fuzzy class MoneyFormatError < ArgumentError; end - MARKS = %w[. , · ’ ˙ '] + [' '] + MARKS = ['.', ',', '·', '’', '˙', "'", ' '].freeze ESCAPED_MARKS = Regexp.escape(MARKS.join) ESCAPED_NON_SPACE_MARKS = Regexp.escape((MARKS - [' ']).join) ESCAPED_NON_DOT_MARKS = Regexp.escape((MARKS - ['.']).join) ESCAPED_NON_COMMA_MARKS = Regexp.escape((MARKS - [',']).join) - NUMERIC_REGEX = /( + NUMERIC_REGEX = %r{( [\+\-]? [\d#{ESCAPED_NON_SPACE_MARKS}][\d#{ESCAPED_MARKS}]* - )/ix + )}ix # 1,234,567.89 - DOT_DECIMAL_REGEX = /\A + DOT_DECIMAL_REGEX = %r{\A [\+\-]? (?: (?:\d+) (?:[#{ESCAPED_NON_DOT_MARKS}]\d{3})+ (?:\.\d{2,})? ) - \z/ix + \z}ix # 1.234.567,89 - COMMA_DECIMAL_REGEX = /\A + COMMA_DECIMAL_REGEX = %r{\A [\+\-]? (?: (?:\d+) (?:[#{ESCAPED_NON_COMMA_MARKS}]\d{3})+ (?:\,\d{2,})? ) - \z/ix + \z}ix # 12,34,567.89 - INDIAN_NUMERIC_REGEX = /\A + INDIAN_NUMERIC_REGEX = %r{\A [\+\-]? (?: (?:\d+) @@ -45,17 +46,17 @@ class MoneyFormatError < ArgumentError; end (?:\,\d{3}) (?:\.\d{2})? ) - \z/ix + \z}ix # 1,1123,4567.89 - CHINESE_NUMERIC_REGEX = /\A + CHINESE_NUMERIC_REGEX = %r{\A [\+\-]? (?: (?:\d+) (?:\,\d{4})+ (?:\.\d{2})? ) - \z/ix + \z}ix def self.parse(input, currency = nil, **options) new.parse(input, currency, **options) @@ -111,11 +112,11 @@ def extract_amount_from_string(input, currency, strict) # remove end of string mark number.sub!(/[#{ESCAPED_MARKS}]\z/, '') - if amount = number[DOT_DECIMAL_REGEX] || number[INDIAN_NUMERIC_REGEX] || number[CHINESE_NUMERIC_REGEX] + if (amount = number[DOT_DECIMAL_REGEX] || number[INDIAN_NUMERIC_REGEX] || number[CHINESE_NUMERIC_REGEX]) return amount.tr(ESCAPED_NON_DOT_MARKS, '') end - if amount = number[COMMA_DECIMAL_REGEX] + if (amount = number[COMMA_DECIMAL_REGEX]) return amount.tr(ESCAPED_NON_COMMA_MARKS, '').sub(',', '.') end diff --git a/lib/money/parser/locale_aware.rb b/lib/money/parser/locale_aware.rb index fb7e3437..6ed4db60 100644 --- a/lib/money/parser/locale_aware.rb +++ b/lib/money/parser/locale_aware.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + class Money module Parser class LocaleAware @@ -7,18 +8,14 @@ class LocaleAware class << self # The +Proc+ called to get the current locale decimal separator. In Rails apps this defaults to the same lookup # ActionView's +number_to_currency+ helper will use to format the monetary amount for display. - def decimal_separator_resolver - @decimal_separator_resolver - end + attr_reader :decimal_separator_resolver # Set the default +Proc+ to determine the current locale decimal separator. # # @example # Money::Parser::LocaleAware.decimal_separator_resolver = # ->() { MyFormattingLibrary.current_locale.decimal.separator } - def decimal_separator_resolver=(proc) - @decimal_separator_resolver = proc - end + attr_writer :decimal_separator_resolver # Parses an input string, normalizing some non-ASCII characters to their equivalent ASCII, then discarding any # character that is not a digit, hyphen-minus or the decimal separator. To prevent user confusion, make sure diff --git a/lib/money/parser/simple.rb b/lib/money/parser/simple.rb index d927602e..d84b24e2 100644 --- a/lib/money/parser/simple.rb +++ b/lib/money/parser/simple.rb @@ -1,8 +1,9 @@ # frozen_string_literal: true + class Money module Parser class Simple - SIGNED_DECIMAL_MATCHER = /\A-?\d*(?:\.\d*)?\z/.freeze + SIGNED_DECIMAL_MATCHER = /\A-?\d*(?:\.\d*)?\z/ class << self # Parses an input string using BigDecimal, it always expects a dot character as a decimal separator and diff --git a/lib/money/rails/job_argument_serializer.rb b/lib/money/rails/job_argument_serializer.rb index 00a582b6..a8011989 100644 --- a/lib/money/rails/job_argument_serializer.rb +++ b/lib/money/rails/job_argument_serializer.rb @@ -19,4 +19,3 @@ def klass end end end - diff --git a/lib/money/railtie.rb b/lib/money/railtie.rb index de63a4ed..56f72d26 100644 --- a/lib/money/railtie.rb +++ b/lib/money/railtie.rb @@ -3,9 +3,9 @@ class Money class Railtie < Rails::Railtie initializer "shopify-money.setup_active_job_serializer" do - ActiveSupport.on_load :active_job do + ActiveSupport.on_load(:active_job) do require_relative "rails/job_argument_serializer" - ActiveJob::Serializers.add_serializers ::Money::Rails::JobArgumentSerializer + ActiveJob::Serializers.add_serializers(::Money::Rails::JobArgumentSerializer) end end diff --git a/lib/money/splitter.rb b/lib/money/splitter.rb index 9119c161..8a34d65b 100644 --- a/lib/money/splitter.rb +++ b/lib/money/splitter.rb @@ -11,7 +11,7 @@ def initialize(money, num) @split = nil end - protected attr_writer :split + protected attr_writer(:split) def split @split ||= begin @@ -35,19 +35,17 @@ def first(count = (count_undefined = true)) each do |money| return money end + elsif count >= size + to_a else - if count >= size - to_a - else - result = Array.new(count) - index = 0 - each do |money| - result[index] = money - index += 1 - break if index == count - end - result + result = Array.new(count) + index = 0 + each do |money| + result[index] = money + index += 1 + break if index == count end + result end end @@ -56,20 +54,18 @@ def last(count = (count_undefined = true)) reverse_each do |money| return money end + elsif count >= size + to_a else - if count >= size - to_a - else - result = Array.new(count) - index = 0 - reverse_each do |money| - result[index] = money - index += 1 - break if index == count - end - result.reverse! - result + result = Array.new(count) + index = 0 + reverse_each do |money| + result[index] = money + index += 1 + break if index == count end + result.reverse! + result end end diff --git a/lib/money/version.rb b/lib/money/version.rb index e5426edd..650b574e 100644 --- a/lib/money/version.rb +++ b/lib/money/version.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + class Money VERSION = "3.0.0" end diff --git a/lib/money_column.rb b/lib/money_column.rb index a6866cb1..9e36e4a3 100644 --- a/lib/money_column.rb +++ b/lib/money_column.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require_relative 'money_column/active_record_hooks' require_relative 'money_column/active_record_type' require_relative 'money_column/railtie' diff --git a/lib/money_column/active_record_hooks.rb b/lib/money_column/active_record_hooks.rb index 30b961c9..904544a0 100644 --- a/lib/money_column/active_record_hooks.rb +++ b/lib/money_column/active_record_hooks.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + module MoneyColumn class CurrencyReadOnlyError < StandardError; end @@ -82,7 +83,7 @@ def money_column(*columns, currency_column: nil, currency: nil, currency_read_on currency_column: currency_column, currency: currency, currency_read_only: currency_read_only, - coerce_null: coerce_null + coerce_null: coerce_null, ) if options[:currency_column] @@ -96,11 +97,11 @@ def money_column(*columns, currency_column: nil, currency: nil, currency_read_on attribute(column_string, MoneyColumn::ActiveRecordType.new) - define_method column do + define_method(column) do read_money_attribute(column_string) end - define_method "#{column}=" do |money| + define_method("#{column}=") do |money| write_money_attribute(column_string, money) end end @@ -109,8 +110,10 @@ def money_column(*columns, currency_column: nil, currency: nil, currency_read_on private def normalize_money_column_options(options) - raise ArgumentError, 'cannot set both :currency_column and :currency options' if options[:currency] && options[:currency_column] - raise ArgumentError, 'must set one of :currency_column or :currency options' unless options[:currency] || options[:currency_column] + raise ArgumentError, + 'cannot set both :currency_column and :currency options' if options[:currency] && options[:currency_column] + raise ArgumentError, + 'must set one of :currency_column or :currency options' unless options[:currency] || options[:currency_column] if options[:currency] options[:currency] = Money::Currency.find!(options[:currency]).to_s.freeze @@ -126,7 +129,7 @@ def normalize_money_column_options(options) def clear_cache_on_currency_change(currency_column) return if money_column_options.any? { |_, opt| opt[:currency_column] == currency_column } - define_method "#{currency_column}=" do |value| + define_method("#{currency_column}=") do |value| clear_money_column_cache super(value) end diff --git a/lib/money_column/active_record_type.rb b/lib/money_column/active_record_type.rb index 2eb69830..403fdab3 100644 --- a/lib/money_column/active_record_type.rb +++ b/lib/money_column/active_record_type.rb @@ -1,7 +1,10 @@ # frozen_string_literal: true -class MoneyColumn::ActiveRecordType < ActiveRecord::Type::Decimal - def serialize(money) - return nil unless money - super(money.to_d) + +module MoneyColumn + class ActiveRecordType < ActiveRecord::Type::Decimal + def serialize(money) + return unless money + super(money.to_d) + end end end diff --git a/lib/money_column/railtie.rb b/lib/money_column/railtie.rb index a85859bc..b2e3e344 100644 --- a/lib/money_column/railtie.rb +++ b/lib/money_column/railtie.rb @@ -1,7 +1,8 @@ # frozen_string_literal: true + module MoneyColumn class Railtie < Rails::Railtie - ActiveSupport.on_load :active_record do + ActiveSupport.on_load(:active_record) do ActiveRecord::Base.send(:include, MoneyColumn::ActiveRecordHooks) end end diff --git a/lib/rubocop/cop/money/missing_currency.rb b/lib/rubocop/cop/money/missing_currency.rb index 852160cf..d869d345 100644 --- a/lib/rubocop/cop/money/missing_currency.rb +++ b/lib/rubocop/cop/money/missing_currency.rb @@ -43,7 +43,7 @@ def on_send(node) add_offense(node, message: 'to_money is missing currency argument') end end - alias on_csend on_send + alias_method :on_csend, :on_send def autocorrect(node) receiver, method, _ = *node @@ -54,7 +54,7 @@ def autocorrect(node) corrector.replace( node.loc.expression, - "#{receiver.source}.#{method}(#{amount&.source || 0}, #{replacement_currency})" + "#{receiver.source}.#{method}(#{amount&.source || 0}, #{replacement_currency})", ) end @@ -63,7 +63,7 @@ def autocorrect(node) elsif to_money_block?(node) corrector.replace( node.loc.expression, - "#{receiver.source}.#{method} { |x| x.to_money(#{replacement_currency}) }" + "#{receiver.source}.#{method} { |x| x.to_money(#{replacement_currency}) }", ) end end @@ -73,7 +73,7 @@ def autocorrect(node) def replacement_currency if cop_config['ReplacementCurrency'] - "'#{cop_config['ReplacementCurrency']}'" + "'#{cop_config["ReplacementCurrency"]}'" else 'Money::NULL_CURRENCY' end diff --git a/lib/rubocop/cop/money/zero_money.rb b/lib/rubocop/cop/money/zero_money.rb index 1642f186..2649d8aa 100644 --- a/lib/rubocop/cop/money/zero_money.rb +++ b/lib/rubocop/cop/money/zero_money.rb @@ -45,7 +45,7 @@ def autocorrect(node) corrector.replace( node.loc.expression, - "#{receiver.source}.new(0, #{replacement_currency})" + "#{receiver.source}.new(0, #{replacement_currency})", ) end end @@ -55,7 +55,7 @@ def autocorrect(node) def replacement_currency(currency_arg) return currency_arg.first.source unless currency_arg.empty? - return "'#{cop_config['ReplacementCurrency']}'" if cop_config['ReplacementCurrency'] + return "'#{cop_config["ReplacementCurrency"]}'" if cop_config['ReplacementCurrency'] 'Money::NULL_CURRENCY' end diff --git a/lib/shopify-money.rb b/lib/shopify-money.rb index 43365e26..a59d4bc0 100644 --- a/lib/shopify-money.rb +++ b/lib/shopify-money.rb @@ -1,2 +1,3 @@ # frozen_string_literal: true + require_relative 'money' diff --git a/money.gemspec b/money.gemspec index dc158daf..a3fbc909 100644 --- a/money.gemspec +++ b/money.gemspec @@ -1,5 +1,6 @@ # -*- encoding: utf-8 -*- # frozen_string_literal: true + require_relative "lib/money/version" Gem::Specification.new do |s| @@ -16,16 +17,15 @@ Gem::Specification.new do |s| s.metadata['allowed_push_host'] = "https://rubygems.org" s.add_development_dependency("bundler") - s.add_development_dependency("simplecov", ">= 0") + s.add_development_dependency("database_cleaner", "~> 2.0") s.add_development_dependency("rails", "~> 7.2") s.add_development_dependency("rspec", "~> 3.2") - s.add_development_dependency("database_cleaner", "~> 2.0") + s.add_development_dependency("simplecov", ">= 0") s.add_development_dependency("sqlite3") s.required_ruby_version = '>= 3.0' - s.files = `git ls-files`.split($/) + s.files = %x(git ls-files).split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } - s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ["lib"] end