Skip to content

Commit

Permalink
Improved docker compose file and database config. Also upgraded Ruboc…
Browse files Browse the repository at this point in the history
…op and fixed lint issues.
  • Loading branch information
haffla committed May 12, 2021
1 parent 45d7d8b commit 2fe70db
Show file tree
Hide file tree
Showing 17 changed files with 107 additions and 98 deletions.
33 changes: 15 additions & 18 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
AllCops:
Include:
- "**/Rakefile"
NewCops: enable
TargetRubyVersion: 2.7.2
SuggestExtensions: false
Exclude:
- db/**/*
- gemfiles/**/*
- vendor/**/*
Style/SpaceBeforeFirstArg:
- "gemfiles/**"
Layout/SpaceBeforeFirstArg:
Enabled: false
Layout/LineLength:
Enabled: false
Layout/SpaceAroundEqualsInParameterDefault:
Enabled: false
Lint/UnusedBlockArgument:
Enabled: false
Expand All @@ -17,8 +20,6 @@ Metrics/ClassLength:
Enabled: false
Metrics/CyclomaticComplexity:
Enabled: false
Metrics/LineLength:
Enabled: false
Metrics/MethodLength:
Enabled: false
Metrics/ModuleLength:
Expand All @@ -29,8 +30,6 @@ Metrics/BlockLength:
Enabled: false
Security/YAMLLoad:
Enabled: false
Style/AlignParameters:
Enabled: false
Style/ClassAndModuleChildren:
Enabled: false
Style/ClassVars:
Expand All @@ -39,25 +38,23 @@ Style/Documentation:
Enabled: false
Style/DoubleNegation:
Enabled: false
Style/FileName:
Naming/FileName:
Enabled: false
Style/GuardClause:
Enabled: false
Style/IndentHash:
Enabled: false
Style/NilComparison:
Enabled: false
Style/OpMethod:
Enabled: false
Style/RescueModifier:
Enabled: false
Style/SignalException:
Enabled: false
Style/SingleLineMethods:
Enabled: false
Style/SpaceAroundEqualsInParameterDefault:
Enabled: false
Style/StringLiterals:
EnforcedStyle: double_quotes
Performance/EndWith:
Naming/BinaryOperatorParameterName:
Enabled: false
Naming/VariableNumber:
Enabled: false
Gemspec/RequiredRubyVersion:
Enabled: false
1 change: 0 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ RUN mkdir -p lib/jsonb_accessor
COPY lib/jsonb_accessor/version.rb ./lib/jsonb_accessor/
COPY *.gemspec Gemfile* ./

RUN gem install bundler
RUN bundle install

COPY . .
53 changes: 33 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ It also adds generic scopes for querying `jsonb` columns.

## Table of Contents

* [Installation](#installation)
* [Usage](#usage)
* [Scopes](#scopes)
* [Single-Table Inheritance](#single-table-inheritance)
* [Dependencies](#dependencies)
* [Validations](#validations)
* [Upgrading](#upgrading)
* [Development](#development)
* [Contributing](#contributing)
- [Installation](#installation)
- [Usage](#usage)
- [Scopes](#scopes)
- [Single-Table Inheritance](#single-table-inheritance)
- [Dependencies](#dependencies)
- [Validations](#validations)
- [Upgrading](#upgrading)
- [Development](#development)
- [Contributing](#contributing)

## Installation

Expand Down Expand Up @@ -158,6 +158,7 @@ Product.all.jsonb_where(:data, reviewed_at: { before: Time.current }, p: { great

Product.all.data_where(reviewed_at: { before: Time.current }, price: { greater_than: 5 })
```

This scope makes use of the `jsonb_contains`, `jsonb_number_where`, and `jsonb_time_where` `scope`s.

### `jsonb_where_not`
Expand Down Expand Up @@ -219,14 +220,14 @@ Product.all.jsonb_number_where(:data, :price_in_cents, :greater_than, 300)

It supports:

* `>`
* `>=`
* `greater_than`
* `greater_than_or_equal_to`
* `<`
* `<=`
* `less_than`
* `less_than_or_equal_to`
- `>`
- `>=`
- `greater_than`
- `greater_than_or_equal_to`
- `<`
- `<=`
- `less_than`
- `less_than_or_equal_to`

and it is indifferent to strings/symbols.

Expand Down Expand Up @@ -259,9 +260,9 @@ Product.all.jsonb_time_where_not(:data, :reviewed_at, :before, 2.days.ago)
## Single-Table Inheritance

One of the big issues with `ActiveRecord` single-table inheritance (STI)
is sparse columns. Essentially, as sub-types of the original table
is sparse columns. Essentially, as sub-types of the original table
diverge further from their parent more columns are left empty in a given
table. Postgres' `jsonb` type provides part of the solution in that
table. Postgres' `jsonb` type provides part of the solution in that
the values in an `jsonb` column does not impose a structure - different
rows can have different values.

Expand Down Expand Up @@ -305,7 +306,7 @@ end
```

From here any attributes specific to any sub-class can be stored in the
`jsonb` column avoiding sparse data. Indices can also be created on
`jsonb` column avoiding sparse data. Indices can also be created on
individual fields in an `jsonb` column.

This approach was originally conceived by Joe Hirn in [this blog
Expand All @@ -326,12 +327,24 @@ See the [upgrade guide](UPGRADE_GUIDE.md).

## Development

### On your local machine

After checking out the repo, run `bin/setup` to install dependencies (make sure postgres is running first).

Run `bin/console` for an interactive prompt that will allow you to experiment.

`rake` will run Rubocop and the specs.

### With Docker

```
# setup
docker-compose build
docker-compose run ruby rake db:create db:migrate
# run test suite
docker-compose run ruby rake spec
```

## Contributing

1. [Fork it](https://github.com/madeintandem/jsonb_accessor/fork)
Expand Down
9 changes: 6 additions & 3 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,21 @@ require "bundler/setup"
require "bundler/gem_tasks"
require "rspec/core/rake_task"
require "rubocop/rake_task"
require "active_record"
require "erb"

RSpec::Core::RakeTask.new
RuboCop::RakeTask.new

require "active_record"
# rubocop:disable Style/MixinUsage
include ActiveRecord::Tasks
# rubocop:enable Style/MixinUsage

root = File.expand_path "..", __FILE__
root = File.expand_path __dir__
db_dir = File.join(root, "db")
DatabaseTasks.root = root
DatabaseTasks.db_dir = db_dir
DatabaseTasks.database_configuration = YAML.load(File.read(File.join(db_dir, "config.yml")))
DatabaseTasks.database_configuration = YAML.load(ERB.new(File.read(File.join(db_dir, "config.yml"))).result)
DatabaseTasks.migrations_paths = [File.join(db_dir, "migrate")]
DatabaseTasks.env = "test"

Expand Down
6 changes: 3 additions & 3 deletions bin/console
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

# rubocop:disable Lint/UselessAssignment

require "bundler/setup"
require "jsonb_accessor"
require "rspec"
require File.expand_path("../../spec/spec_helper.rb", __FILE__)
require File.expand_path("../spec/spec_helper.rb", __dir__)

dbconfig = YAML.load(File.open("db/config.yml"))
ActiveRecord::Base.establish_connection(dbconfig["development"])

# rubocop:disable Lint/UselessAssignment
x = Product.new
# rubocop:enable Lint/UselessAssignment

Pry.start
2 changes: 1 addition & 1 deletion db/config.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
default: &default
adapter: postgresql
database: jsonb_accessor
host: database
host: <%= ENV.fetch("DATABASE_HOST") { "127.0.0.1" } %>
user: postgres

test:
Expand Down
2 changes: 2 additions & 0 deletions db/migrate/20150407031737_set_up_testing_db.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

class SetUpTestingDb < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
Expand Down
6 changes: 3 additions & 3 deletions db/schema.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
Expand All @@ -10,8 +12,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2015_04_07_031737) do

ActiveRecord::Schema.define(version: 20_150_407_031_737) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

Expand All @@ -32,5 +33,4 @@
t.datetime "datetime_type"
t.decimal "decimal_type"
end

end
8 changes: 5 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@ version: '3'

services:
ruby:
environment:
- DATABASE_HOST=postgres
build:
args:
- RUBY_VERSION=${RUBY_VERSION:-2.7.2}
context: .
volumes:
- '.:/usr/src/app'
links:
- database
depends_on:
- postgres

database:
postgres:
image: postgres:12
environment:
- POSTGRES_HOST_AUTH_METHOD=trust
Expand Down
7 changes: 3 additions & 4 deletions jsonb_accessor.gemspec
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# coding: utf-8
# frozen_string_literal: true

lib = File.expand_path("../lib", __FILE__)
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "jsonb_accessor/version"

Expand All @@ -27,12 +26,12 @@ Gem::Specification.new do |spec|
spec.add_dependency "pg", ">= 0.18.1"

spec.add_development_dependency "appraisal", "~> 2.2.0"
spec.add_development_dependency "database_cleaner", "~> 1.6.0"
spec.add_development_dependency "awesome_print"
spec.add_development_dependency "database_cleaner", "~> 1.6.0"
spec.add_development_dependency "pry"
spec.add_development_dependency "pry-doc"
spec.add_development_dependency "pry-nav"
spec.add_development_dependency "rake", ">= 12.3.3"
spec.add_development_dependency "rspec", "~> 3.6.0"
spec.add_development_dependency "rubocop", "~> 0.48.1"
spec.add_development_dependency "rubocop", "~> 1"
end
4 changes: 2 additions & 2 deletions lib/jsonb_accessor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ module JsonbAccessor
end

ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.send(:include, JsonbAccessor)
ActiveRecord::Base.send(:include, JsonbAccessor::QueryBuilder)
ActiveRecord::Base.include JsonbAccessor
ActiveRecord::Base.include JsonbAccessor::QueryBuilder
end
2 changes: 1 addition & 1 deletion lib/jsonb_accessor/macro.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def jsonb_accessor(jsonb_attribute, field_types)
# each time it is evaluated.
all_defaults_mapping_proc =
if all_defaults_mapping.present?
-> { all_defaults_mapping.map { |key, value| [key, value.respond_to?(:call) ? value.call : value] }.to_h }
-> { all_defaults_mapping.transform_values { |value| value.respond_to?(:call) ? value.call : value }.to_h }
end
attribute jsonb_attribute, :jsonb, default: all_defaults_mapping_proc if all_defaults_mapping_proc.present?

Expand Down
4 changes: 1 addition & 3 deletions lib/jsonb_accessor/query_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ module QueryBuilder
excludes_attributes = {}

attributes.each do |name, value|
if value.is_a?(Range)
raise JsonbAccessor::QueryHelper::NotSupported, "`jsonb_where_not` scope does not accept ranges as arguments. Given `#{value}` for `#{name}` field"
end
raise JsonbAccessor::QueryHelper::NotSupported, "`jsonb_where_not` scope does not accept ranges as arguments. Given `#{value}` for `#{name}` field" if value.is_a?(Range)

if JsonbAccessor::QueryHelper.number_query_arguments?(value)
value.each { |operator, query_value| query = query.jsonb_number_where_not(column_name, name, operator, query_value) }
Expand Down
8 changes: 2 additions & 6 deletions lib/jsonb_accessor/query_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ module QueryHelper

class << self
def validate_column_name!(query, column_name)
if query.model.columns.none? { |column| column.name == column_name.to_s }
raise InvalidColumnName, "a column named `#{column_name}` does not exist on the `#{query.model.table_name}` table"
end
raise InvalidColumnName, "a column named `#{column_name}` does not exist on the `#{query.model.table_name}` table" if query.model.columns.none? { |column| column.name == column_name.to_s }
end

def validate_field_name!(query, column_name, field_name)
Expand All @@ -56,9 +54,7 @@ def validate_field_name!(query, column_name, field_name)
end

def validate_direction!(option)
if ORDER_DIRECTIONS.exclude?(option)
raise InvalidDirection, "`#{option}` is not a valid direction for ordering, only `asc` and `desc` are accepted"
end
raise InvalidDirection, "`#{option}` is not a valid direction for ordering, only `asc` and `desc` are accepted" if ORDER_DIRECTIONS.exclude?(option)
end

def convert_keys_to_store_keys(attributes, store_key_mapping)
Expand Down
Loading

0 comments on commit 2fe70db

Please sign in to comment.