Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pyromaniac committed Dec 9, 2013
0 parents commit 1e3e604
Show file tree
Hide file tree
Showing 52 changed files with 2,244 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--color
--backtrace
--order random
1 change: 1 addition & 0 deletions .rvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rvm use 1.9.3@chewy --create
7 changes: 7 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
language: ruby
rvm:
- 1.9.3
- 2.0.0
- rbx
services:
- elasticsearch
12 changes: 12 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
source 'https://rubygems.org'

# Specify your gem's dependencies in chewy.gemspec
gemspec

group :test do
gem 'guard'
gem 'guard-rspec'
gem 'rb-inotify', require: false
gem 'rb-fsevent', require: false
gem 'rb-fchange', require: false
end
22 changes: 22 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Copyright (c) 2013 pyromaniac

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Chewy

TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

gem 'chewy'

And then execute:

$ bundle

Or install it yourself as:

$ gem install chewy

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it ( http://github.com/<my-github-username>/chewy/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
6 changes: 6 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

task :default => :spec
33 changes: 33 additions & 0 deletions chewy.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'chewy/version'

Gem::Specification.new do |spec|
spec.name = 'chewy'
spec.version = Chewy::VERSION
spec.authors = ["pyromaniac"]
spec.email = ["[email protected]"]
spec.summary = %q{TODO: Write a short summary. Required.}
spec.description = %q{TODO: Write a longer description. Optional.}
spec.homepage = ""
spec.license = "MIT"

spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]

spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'sqlite3'
spec.add_development_dependency 'kaminari'
spec.add_development_dependency 'activerecord', '>= 3.2'
spec.add_development_dependency 'database_cleaner'
spec.add_development_dependency 'rubysl', '~> 2.0' if RUBY_ENGINE == 'rbx'

spec.add_dependency 'activesupport', '>= 3.2'
spec.add_dependency 'elasticsearch'
spec.add_dependency 'elasticsearch'
end
55 changes: 55 additions & 0 deletions lib/chewy.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
require 'active_support/concern'
require 'active_support/core_ext'
require 'active_support/json'
require 'singleton'

require 'elasticsearch'

require 'chewy/version'
require 'chewy/config'
require 'chewy/index'
require 'chewy/type'
require 'chewy/query'
require 'chewy/fields/base'
require 'chewy/fields/default'
require 'chewy/fields/root'

ActiveSupport.on_load(:active_record) do
extend Chewy::Type::Observe::ActiveRecordMethods
end

module Chewy
class Error < StandardError
end

class UndefinedIndex < Error
end

class UndefinedType < Error
end

class UnderivableType < Error
end

def self.derive_type name
return name if name.is_a?(Class) && name < Chewy::Type

index_name, type_name = name.split('#', 2)
class_name = "#{index_name.camelize}Index"
index = class_name.safe_constantize
raise Chewy::UnderivableType.new("Can not find index named `#{class_name}`") unless index && index < Chewy::Index
type = if type_name.present?
index.types[type_name] or raise Chewy::UnderivableType.new("Index `#{class_name}` doesn`t have type named `#{type_name}`")
elsif index.types.values.one?
index.types.values.first
else
raise Chewy::UnderivableType.new("Index `#{class_name}` has more than one type, please specify type via `#{index_name}#type_name`")
end
end

def self.config
Chewy::Config.instance
end

singleton_class.delegate *Chewy::Config.delegated, to: :config
end
48 changes: 48 additions & 0 deletions lib/chewy/config.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
module Chewy
class Config
include Singleton

attr_accessor :observing_enabled, :client_options

def self.delegated
public_instance_methods - self.superclass.public_instance_methods - Singleton.public_instance_methods
end

def initialize
@observing_enabled = true
@client_options = {}
end

def client_options
yaml_options = if defined? Rails
file = Rails.root.join(*%w(config chewy.yml))
YAML.load_file(file)[Rails.env].try(:deep_symbolize_keys) if File.exists?(file)
end
@client_options.merge(yaml_options || {})
end

def atomic?
atomic_stash.any?
end

def atomic
atomic_stash.push({})
result = yield
atomic_stash.last.each { |type, ids| type.import(ids) }
result
ensure
atomic_stash.pop
end

def atomic_stash(type = nil, *ids)
if type
raise ArgumentError.new('Only Chewy::Type accepted as the first argument') unless type < Chewy::Type
atomic_stash.push({}) unless atomic_stash.last
atomic_stash.last[type] ||= []
atomic_stash.last[type] |= ids.flatten
else
Thread.current[:chewy_atomic] ||= []
end
end
end
end
49 changes: 49 additions & 0 deletions lib/chewy/fields/base.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
module Chewy
module Fields
class Base
attr_reader :name, :options, :value

def initialize(name, options = {})
@name, @options, @nested = name.to_sym, options, {}
@value = @options.delete(:value)
end

def multi_field?
@options[:type] == 'multi_field'
end

def compose(object)
result = value ? value.call(object) : object.send(name)

result = if result.is_a?(Enumerable)
result.map { |object| nested_compose(object) }
else
nested_compose(result)
end if nested.any? && !multi_field?

{name => result.as_json}
end

def nested(field = nil)
if field
@nested[field.name] = field
else
@nested
end
end

def mappings_hash
subfields = nested.any? ? {
(multi_field? ? :fields : :properties) => nested.values.map(&:mappings_hash).inject(:merge)
} : {}
{name => options.merge(subfields)}
end

private

def nested_compose(value)
nested.values.map { |field| field.compose(value) }.inject(:merge)
end
end
end
end
10 changes: 10 additions & 0 deletions lib/chewy/fields/default.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Chewy
module Fields
class Default < Chewy::Fields::Base
def initialize(name, options = {})
options.reverse_merge!(type: 'string')
super(name, options)
end
end
end
end
10 changes: 10 additions & 0 deletions lib/chewy/fields/root.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module Chewy
module Fields
class Root < Chewy::Fields::Base
def initialize(name, options = {})
options.reverse_merge!(value: ->(_){_})
super(name, options)
end
end
end
end
79 changes: 79 additions & 0 deletions lib/chewy/index.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
require 'chewy/index/actions'
require 'chewy/index/client'
require 'chewy/index/search'

module Chewy
class Index
include Actions
include Client
include Search

class_attribute :types
self.types = {}

class_attribute :_settings
self._settings = {}

def self.define_type(type_class = nil, &block)
if block
name = type_class.presence || index_name.singularize
type_class = Class.new(Chewy::Type) { type_name name }
type_class.index = self
type_class.class_eval &block
else
type_class.index = self
end

self.types = types.merge(type_class.type_name => type_class)

class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{type_class.type_name}
types['#{type_class.type_name}']
end
RUBY
end

def self.settings(params)
self._settings = params
end

def self.index_name(suggest = nil)
if suggest
@index_name = suggest.to_s
else
@index_name ||= (name.gsub(/Index\Z/, '').demodulize.underscore if name)
end
@index_name or raise UndefinedIndex
end

def self.settings_hash
_settings.present? ? {settings: _settings} : {}
end

def self.mappings_hash
mappings = types.values.map(&:mappings_hash).inject(:merge)
mappings.present? ? {mappings: mappings} : {}
end

def self.index_params
[settings_hash, mappings_hash].inject(:merge)
end

def self.search_index
self
end

def self.search_type
types.keys
end

def self.import
types.values.all? { |t| t.import }
end

def self.reset
index_purge!
import
end
end
end
Loading

0 comments on commit 1e3e604

Please sign in to comment.