repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
oneplanetliving/hyper-router
|
lib/hyper-router/match.rb
|
<reponame>oneplanetliving/hyper-router
module HyperRouter
class Match
include Native
def initialize(native)
@native = native
end
def to_n
@native
end
alias_native :params
alias_native :is_exact, :isExact
alias_native :path
alias_native :url
end
end
|
oneplanetliving/hyper-router
|
spec/test_app/app/hyperloop/components/basic_example.rb
|
class App < Hyperstack::Router
#prerender_path :url_path, default: '/'
history :browser
route do
DIV do
UL do
LI { Link('/', id: :home_link) { 'Home' } }
LI { Link('/about', id: :about_link) { 'About' } }
LI { Link('/topics', id: :topics_link) { 'Topics' } }
end
Route('/', exact: true, mounts: Home)
Route('/about', mounts: About)
Route('/topics', mounts: Topics)
end
end
end
class Home < Hyperstack::Router::Component
render(:div) do
H2() { 'Home' }
end
end
class About < Hyperstack::Router::Component
render(:div) do
H2 { 'About Page' }
end
end
class Topics < Hyperstack::Router::Component
render(:div) do
H2 { 'Topics Page' }
UL() do
LI { Link("#{match.url}/rendering") { 'Rendering with React' } }
LI { Link("#{match.url}/components", id: :components_link) { 'Components' } }
LI { Link("#{match.url}/props-v-state") { 'Props v. State' } }
end
Route("#{match.url}/:topic_id", mounts: Topic)
Route(match.url, exact: true) do
H3 { 'Please select a topic.' }
end
end
end
class Topic < Hyperstack::Router::Component
render(:div) do
H3 { "more on #{match.params[:topic_id]}..." }
end
end
|
oneplanetliving/hyper-router
|
lib/hyperstack/router/base.rb
|
module Hyperstack
class Router
module Base
def self.included(base)
base.extend(HyperRouter::ClassMethods)
base.include(HyperRouter::InstanceMethods)
base.include(HyperRouter::ComponentMethods)
base.class_eval do
after_mount do
@_react_router_unlisten = history.listen do |location, _action|
React::State.set_state(HyperRouter, :location, location)
end
end
before_unmount do
@_react_router_unlisten.call if @_react_router_unlisten
end
end
end
end
end
end
|
oneplanetliving/hyper-router
|
config.ru
|
# config.ru
require 'bundler'
Bundler.require
require "opal-rspec"
#require "react/source"
Opal.append_path File.expand_path('../spec', __FILE__)
run Opal::Server.new { |s|
s.main = 'opal/rspec/sprockets_runner'
s.append_path 'spec'
#s.append_path File.dirname(::React::Source.bundled_path_for("react-with-addons.js"))
s.debug = true
s.index_path = 'spec/index.html.erb'
}
|
oneplanetliving/hyper-router
|
lib/hyperstack/router/browser.rb
|
module Hyperstack
class Router
module Browser
def self.included(base)
base.extend(HyperRouter::ClassMethods)
base.history(:browser)
base.include(HyperRouter::InstanceMethods)
base.include(HyperRouter::ComponentMethods)
end
end
end
end
|
oneplanetliving/hyper-router
|
spec/hyper-router/basic_dsl_spec.rb
|
<gh_stars>0
require 'spec_helper'
describe "Hyperstack::Router", js: true do
it "can route" do
visit '/'
page.find('a', id: 'about_link').click
expect(page).to have_content('About Page')
expect(page.current_path).to eq('/about')
page.find('a', id: 'topics_link').click
expect(page).to have_content('Topics Page')
expect(page.current_path).to eq('/topics')
page.find('a', id: 'components_link').click
expect(page).to have_content('more on components...')
expect(page.current_path).to eq('/topics/components')
end
end
|
oneplanetliving/hyper-router
|
lib/hyperstack/router/static.rb
|
module Hyperstack
class Router
module Static
module ClassMethods
def route(&block)
prerender_router(&block)
end
end
def self.included(base)
base.extend(HyperRouter::ClassMethods)
base.extend(ClassMethods)
base.include(HyperRouter::InstanceMethods)
base.include(HyperRouter::ComponentMethods)
end
end
end
end
|
oneplanetliving/hyper-router
|
lib/react/router/dom.rb
|
<filename>lib/react/router/dom.rb
module React
class Router
class DOM < React::NativeLibrary
imports 'ReactRouterDOM'
end
end
end
|
oneplanetliving/hyper-router
|
lib/hyperstack/router/mixin.rb
|
<filename>lib/hyperstack/router/mixin.rb<gh_stars>0
module Hyperstack
class Router
module Mixin
class << self
def included(base)
base.include(Hyperstack::Component::Mixin)
base.include(HyperRouter::ComponentMethods)
base.class_eval do
param :match, default: nil
param :location, default: nil
param :history, default: nil
define_method(:match) do
params.match
end
define_method(:location) do
params.location
end
define_method(:history) do
params.history
end
end
end
end
end
end
end
|
oneplanetliving/hyper-router
|
lib/hyper-router.rb
|
# rubocop:disable Style/FileName
require 'hyper-react'
if RUBY_ENGINE == 'opal'
require 'react/router'
require 'react/router/dom'
require 'react/router/history'
require 'hyper-router/isomorphic_methods'
require 'hyper-router/history'
require 'hyper-router/location'
require 'hyper-router/match'
require 'hyper-router/class_methods'
require 'hyper-router/component_methods'
require 'hyper-router/instance_methods'
require 'hyperstack/router/base'
require 'hyperstack/router/browser'
require 'hyperstack/router/mixin'
require 'hyperstack/router/component'
require 'hyperstack/router/hash'
require 'hyperstack/router/memory'
require 'hyperstack/router/static'
require 'hyperstack/router'
else
require 'opal'
require 'hyper-router/isomorphic_methods'
require 'hyper-router/version'
Opal.append_path File.expand_path('../', __FILE__).untaint
end
|
oneplanetliving/hyper-router
|
lib/hyper-router/class_methods.rb
|
<reponame>oneplanetliving/hyper-router<filename>lib/hyper-router/class_methods.rb
module HyperRouter
class NoHistoryError < StandardError; end
module ClassMethods
def history(*args)
if args.count > 0
@__history_type = args.first
elsif @__history_type
@__history ||= send(:"#{@__history_type}_history")
end
end
def location
Location.new(`#{history.to_n}.location`)
end
def route(&block)
if React::IsomorphicHelpers.on_opal_server?
prerender_router(&block)
else
render_router(&block)
end
end
private
def browser_history
@__browser_history ||= React::Router::History.current.create_browser_history
end
def hash_history(*args)
@__hash_history ||= React::Router::History.current.create_hash_history(*args)
end
def memory_history(*args)
@__memory_history ||= React::Router::History.current.create_memory_history(*args)
end
def render_router(&block)
define_method(:render) do
self.class.history :browser unless history
React::Router::Router(history: history.to_n) do
instance_eval(&block)
end
end
end
def prerender_router(&block)
define_method(:render) do
location = {}.tap do |hash|
pathname, search = IsomorphicMethods.request_fullpath.split('?', 2)
hash[:pathname] = pathname
hash[:search] = search ? "?#{search}" : ''
end
React::Router::StaticRouter(location: location.to_n, context: {}.to_n) do
instance_eval(&block)
end
end
end
end
end
|
oneplanetliving/hyper-router
|
lib/hyperstack/router/memory.rb
|
<gh_stars>0
module Hyperstack
class Router
module Memory
def self.included(base)
base.extend(HyperRouter::ClassMethods)
base.history(:memory)
base.include(HyperRouter::InstanceMethods)
base.include(HyperRouter::ComponentMethods)
end
end
end
end
|
zoras/rubytoolbox
|
app/models/category_group.rb
|
# frozen_string_literal: true
class CategoryGroup < ApplicationRecord
self.primary_key = :permalink
has_many :categories,
-> { order(name: :asc) },
foreign_key: :category_group_permalink,
dependent: :destroy
def self.for_welcome_page
order(name: :asc).includes(:categories)
end
end
|
zoras/rubytoolbox
|
spec/controllers/welcome_controller_spec.rb
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe WelcomeController, type: :controller do
describe "GET home" do
let(:do_request) { get :home }
it "responds with success" do
expect(do_request).to have_http_status :success
end
it "renders template home" do
expect(do_request).to render_template :home
end
it "assigns CategoryGroup.for_welcome_page" do
allow(CategoryGroup).to receive(:for_welcome_page).and_return("The Groups")
do_request
expect(assigns(:groups)).to be == "The Groups"
end
end
end
|
zoras/rubytoolbox
|
config.ru
|
# frozen_string_literal: true
# This file is used by Rack-based servers to start the application.
require_relative "config/environment"
use Rack::SslEnforcer if Rails.env.production?
use Rack::CanonicalHost, ENV["CANONICAL_HOST"] if ENV["CANONICAL_HOST"].present?
run Rails.application
|
zoras/rubytoolbox
|
app/models/project.rb
|
# frozen_string_literal: true
class Project < ApplicationRecord
self.primary_key = :permalink
has_many :categorizations,
primary_key: :permalink,
foreign_key: :project_permalink,
validate: false,
dependent: :destroy
has_many :categories, through: :categorizations
def description
Forgery(:lorem_ipsum).words(20 + rand(20))
end
def score
rand(100).round(2)
end
end
|
zoras/rubytoolbox
|
app/controllers/welcome_controller.rb
|
<filename>app/controllers/welcome_controller.rb
# frozen_string_literal: true
class WelcomeController < ApplicationController
def home
@groups = CategoryGroup.for_welcome_page
render action: :home
end
end
|
zoras/rubytoolbox
|
spec/controllers/categories_controller_spec.rb
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe CategoriesController, type: :controller do
describe "GET show" do
describe "for unknown category" do
let(:do_request) { get :show, params: { id: "foobar" } }
it "raises ActiveRecord::RecordNotFound" do
expect { do_request }.to raise_error ActiveRecord::RecordNotFound
end
end
describe "for known category" do
let(:do_request) { get :show, params: { id: category.permalink } }
let(:category) do
Category.create! permalink: "category",
name: "Category",
category_group: CategoryGroup.create!(name: "Group", permalink: "group")
end
it "responds with success" do
expect(do_request).to have_http_status :success
end
it "renders template show" do
expect(do_request).to render_template :show
end
it "assigns Category.find_for_show!" do
allow(Category).to receive(:find_for_show!).and_return("The Category")
do_request
expect(assigns(:category)).to be == "The Category"
end
end
end
end
|
zoras/rubytoolbox
|
app/controllers/categories_controller.rb
|
# frozen_string_literal: true
class CategoriesController < ApplicationController
def show
@category = Category.find_for_show! params[:id]
end
end
|
zoras/rubytoolbox
|
spec/models/project_spec.rb
|
<reponame>zoras/rubytoolbox<filename>spec/models/project_spec.rb<gh_stars>0
# frozen_string_literal: true
require "rails_helper"
RSpec.describe Project, type: :model do
describe "#score" do
it "is a random number" do
expect(described_class.new.score).to be_a Float
end
end
describe "#description" do
it "is a random string" do
expect(described_class.new.description).to be_a String
end
end
end
|
zoras/rubytoolbox
|
db/migrate/20171026220117_add_categories_groups_association.rb
|
<gh_stars>0
# frozen_string_literal: true
class AddCategoriesGroupsAssociation < ActiveRecord::Migration[5.1]
# This is fine here, we're working on an empty DB
# rubocop:disable Rails/NotNullColumn:
def change
add_column :categories, :category_group_permalink, :string, null: false
add_index :categories, :category_group_permalink
add_foreign_key :categories, :category_groups, column: :category_group_permalink, primary_key: :permalink
end
end
|
zoras/rubytoolbox
|
app/models/category.rb
|
# frozen_string_literal: true
class Category < ApplicationRecord
self.primary_key = :permalink
belongs_to :category_group,
primary_key: :permalink,
foreign_key: :category_group_permalink
has_many :categorizations,
primary_key: :permalink,
foreign_key: :category_permalink,
dependent: :destroy
has_many :projects, through: :categorizations
def self.find_for_show!(permalink)
includes(:category_group, :projects).find(permalink)
end
end
|
zoras/rubytoolbox
|
app/services/catalog_import.rb
|
<filename>app/services/catalog_import.rb
# frozen_string_literal: true
class CatalogImport
attr_accessor :catalog_data
private :catalog_data=
def initialize(catalog_data)
self.catalog_data = catalog_data
end
def perform
upsert_category_groups
destroy_obsolete_category_groups
destroy_obsolete_categories
link_projects_to_categories
destroy_obsolete_categorizations
end
private
def category_group_data
catalog_data["category_groups"]
end
def category_data
@category_data ||= category_group_data.map { |g| g["categories"] }.flatten
end
def project_data
@project_data ||= category_data.map { |c| c["projects"] }.flatten.uniq
end
def upsert_category_groups
category_group_data.each do |category_group_data|
group = CategoryGroup.find_or_initialize_by(permalink: category_group_data["permalink"])
group.update_attributes! name: category_group_data["name"],
description: category_group_data["description"]
upsert_categories categories_data: category_group_data["categories"], group: group
end
end
def destroy_obsolete_category_groups
obsolete_groups = CategoryGroup.pluck(:permalink) - category_group_data.map { |g| g["permalink"] }
obsolete_groups.each { |permalink| CategoryGroup.find(permalink).destroy }
end
def upsert_categories(categories_data:, group:)
categories_data.each do |category_data|
category = Category.find_or_initialize_by(permalink: category_data["permalink"])
category.update_attributes! name: category_data["name"],
description: category_data["description"],
category_group: group
upsert_projects category_data["projects"]
end
end
def destroy_obsolete_categories
obsolete_categories = Category.pluck(:permalink) - category_data.map { |g| g["permalink"] }
obsolete_categories.each { |permalink| Category.find(permalink).destroy }
end
def upsert_projects(projects)
projects.each do |project|
Project.find_or_initialize_by(permalink: project).save!
end
end
def link_projects_to_categories
project_data.each do |project_permalink|
Project.find(project_permalink).update_attributes! categories: categories_for_project_permalink(project_permalink)
end
end
def categories_for_project_permalink(project_permalink)
relevant_category_permalinks = category_data
.select { |c| c["projects"].include? project_permalink }
.map { |c| c["permalink"] }
Category.where(permalink: relevant_category_permalinks)
end
def destroy_obsolete_categorizations
Categorization.where.not(project_permalink: project_data).destroy_all
end
end
|
zoras/rubytoolbox
|
config/routes.rb
|
<reponame>zoras/rubytoolbox
# frozen_string_literal: true
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :categories, only: %i[show]
root "welcome#home"
end
|
uhoh-itsmaciek/attr_pouch
|
lib/attr_pouch.rb
|
<filename>lib/attr_pouch.rb
require 'pg'
require 'sequel'
require 'attr_pouch/errors'
module AttrPouch
def self.configure
@@config ||= Config.new
yield @@config
end
def self.config
@@config ||= Config.new
end
def self.included(base)
base.extend(ClassMethods)
# we can't just independently define this in ClassMethods since
# `dataset_module` is only defined on Sequel::Model subclasses
base.dataset_module do
define_method(:where_pouch) do |pouch_field, expr_hash|
ds = self
pouch = model.pouch(pouch_field)
if pouch.nil?
raise ArgumentError,
"No pouch defined for #{pouch_field}"
end
if pouch.json?
raise UnsupportedError, "Dataset queries not supported for columns of type json"
end
expr_hash.each do |key, value|
key = key.to_s
field = pouch.field_definition(key)
if field.nil?
raise ArgumentError,
"No field #{key} defined for pouch #{pouch_field}"
end
if value.respond_to?(:each)
value.each_with_index do |v,i|
condition = pouch.store.contains(pouch.wrap(key => field.encode(v)))
ds = i == 0 ? ds.where(condition) : ds.or(condition)
end
elsif value.nil?
ds = ds.where(pouch.store.has_key?(key) => false)
.or(pouch.store.contains(pouch.wrap(key => field.encode(value))))
else
ds = ds.where(pouch.store
.contains(pouch.wrap(key => field.encode(value))))
end
end
ds
end
end
end
class Field
attr_reader :pouch, :name, :type, :raw_type, :opts
def self.encode(type, &block)
@@encoders ||= {}
@@encoders[type] = block
end
def self.decode(type, &block)
@@decoders ||= {}
@@decoders[type] = block
end
def self.encoders; @@encoders; end
def self.decoders; @@decoders; end
def self.infer_type(field=nil, &block)
if block_given?
@@type_inferrer = block
else
if @@type_inferrer.nil?
raise InvalidFieldError, "No type inference configured"
else
type = @@type_inferrer.call(field)
if type.nil?
raise InvalidFieldError, "Could not infer type of field #{field}"
end
type
end
end
end
def initialize(pouch, name, opts)
@name = name.to_s
if opts.has_key?(:type)
@type = to_class(opts.fetch(:type))
else
@type = self.class.infer_type(self)
end
@pouch = pouch
@opts = opts
end
def raw_type
@opts.fetch(:type, nil)
end
def alias_as(new_name)
if new_name == name
self
else
self.class.new(pouch, new_name, opts)
end
end
def required?
!(has_default? || deletable?)
end
def has_default?
opts.has_key?(:default)
end
def default
opts.fetch(:default, nil)
end
def mutable?
opts.fetch(:mutable, true)
end
def deletable?
opts.fetch(:deletable, false)
end
def previous_aliases
was = opts.fetch(:was, [])
aliases = if was.respond_to?(:to_a)
was.to_a
else
[ was ]
end
aliases.map(&:to_s)
end
def all_names
[ name ] + previous_aliases
end
def write(store, value, encode: true)
if store.has_key?(name)
raise ImmutableFieldUpdateError unless mutable?
end
if encode
value = self.encode(value)
end
if !store.has_key?(name) || value != store[name]
store[name] = value
previous_aliases.each { |a| store.delete(a) }
true
else
false
end
end
def read(store, decode: true)
present_as = all_names.find { |n| !store.nil? && store.has_key?(n) }
if store.nil? || present_as.nil?
if required?
raise MissingRequiredFieldError,
"Expected field #{inspect} to exist"
else
default if decode
end
elsif present_as == name
raw = store.fetch(name)
decode ? decode(raw) : raw
else
alias_as(present_as).read(store)
end
end
def decode(value)
decoder.call(self, value) unless value.nil?
end
def encode(value)
encoder.call(self, value) unless value.nil?
end
def decoder
@decoder ||= self.class.decoders
.find(method(:ensure_decoder)) do |decoder_type, _|
compatible_codec?(decoder_type)
end.last
end
def encoder
@encoder ||= self.class.encoders
.find(method(:ensure_encoder)) do |encoder_type, _|
compatible_codec?(encoder_type)
end.last
end
private
def compatible_codec?(codec_type)
if self.type.is_a?(Class) && codec_type.is_a?(Class)
self.type <= codec_type
else
self.type == codec_type
end
rescue
false
end
def ensure_encoder
raise MissingCodecError,
"No encoder found for #{inspect}"
end
def ensure_decoder
raise MissingCodecError,
"No decoder found for #{inspect}"
end
def to_class(type)
return type if type.is_a?(Class) || type.is_a?(Symbol)
type.to_s.split('::').inject(Object) do |moodule, klass|
moodule.const_get(klass)
end
end
end
class Config
def initialize
@encoders = {}
@decoders = {}
end
def infer_type(&block)
if block_given?
Field.infer_type(&block)
else
raise ArgumentError, "Expected block to infer types with"
end
end
def encode(type, &block)
Field.encode(type, &block)
end
def decode(type, &block)
Field.decode(type, &block)
end
end
class Pouch
VALID_FIELD_NAME_REGEXP = %r{\A[a-zA-Z0-9_]+\??\z}
def initialize(host, storage_field)
@host = host
@storage_field = storage_field.to_sym
@fields = {}
end
def field_definition(name)
@fields[name.to_s]
end
def hstore?
pouch_column_info.fetch(:db_type) == 'hstore'
end
def json?
pouch_column_info.fetch(:db_type) == 'json'
end
def jsonb?
pouch_column_info.fetch(:db_type) == 'jsonb'
end
def either_json?
json? || jsonb?
end
def pouch_column_info
@host.db_schema.find { |k,_| k == @storage_field }.last
end
def wrap(hash)
if hstore?
Sequel.hstore(hash)
elsif json?
Sequel.pg_json(hash)
elsif jsonb?
Sequel.pg_jsonb(hash)
else
raise InvalidPouchError, "Pouch must use hstore, json, or jsonb column"
end
end
def store
if hstore?
Sequel.hstore(@storage_field)
elsif json?
Sequel.pg_json_op(@storage_field)
elsif jsonb?
Sequel.pg_jsonb_op(@storage_field)
else
raise InvalidPouchError, "Pouch must use hstore, json, or jsonb column"
end
end
def field(name, opts={})
unless VALID_FIELD_NAME_REGEXP.match(name)
raise InvalidFieldError, "Field name must match #{VALID_FIELD_NAME_REGEXP}"
end
field = Field.new(self, name, opts)
@fields[name.to_s] = field
storage_field = @storage_field
default_store = wrap({})
@host.class_eval do
define_method(name) do
store = self[storage_field]
field.read(store)
end
define_method("#{name.to_s.sub(/\?\z/, '')}=") do |value|
store = self[storage_field]
was_nil = store.nil?
store = default_store.dup if was_nil
changed = field.write(store, value)
if was_nil
self[storage_field] = store
else
modified! storage_field if changed
end
end
if field.deletable?
delete_method = "delete_#{name.to_s.sub(/\?\z/, '')}"
define_method(delete_method) do
store = self[storage_field]
unless store.nil?
field.all_names.each { |a| store.delete(a) }
modified! storage_field
end
end
define_method("#{delete_method}!") do
self.public_send(delete_method)
save_changes
end
end
if opts.has_key?(:raw_field)
raw_name = opts[:raw_field]
define_method(raw_name) do
store = self[storage_field]
field.read(store, decode: false)
end
define_method("#{raw_name.to_s.sub(/\?\z/, '')}=") do |value|
store = self[storage_field]
was_nil = store.nil?
store = default_store.dup if was_nil
changed = field.write(store, value, encode: false)
if was_nil
self[storage_field] = store
else
modified! storage_field if changed
end
end
end
end
end
end
module ClassMethods
def pouch(field, &block)
if block_given?
pouch = Pouch.new(self, field)
@pouches ||= {}
@pouches[field] = pouch
pouch.instance_eval(&block)
else
@pouches[field]
end
end
end
end
AttrPouch.configure do |config|
config.encode(String) do |field, value|
value.to_s
end
config.decode(String) do |field, value|
value
end
config.encode(Integer) do |field, value|
value.to_s
end
config.decode(Integer) do |field, value|
Integer(value)
end
config.encode(Float) do |field, value|
value.to_s
end
config.decode(Float) do |field, value|
Float(value)
end
config.encode(Time) do |field, value|
value.strftime('%Y-%m-%d %H:%M:%S.%N')
end
config.decode(Time) do |field, value|
Time.parse(value)
end
config.encode(:bool) do |field, value|
value.to_s
end
config.decode(:bool) do |field, value|
value.to_s == 'true'
end
config.encode(Sequel::Model) do |field, value|
klass = field.type
value[klass.primary_key]
end
config.decode(Sequel::Model) do |field, value|
klass = field.type
klass[value]
end
config.infer_type do |field|
case field.name
when /\Anum_|_(?:count|size)\z/
Integer
when /_(?:at|by)\z/
Time
when /\?\z/
:bool
else
String
end
end
end
|
uhoh-itsmaciek/attr_pouch
|
lib/attr_pouch/errors.rb
|
<gh_stars>1-10
module AttrPouch
# Base class for AttrPouch errors
class Error < StandardError; end
class MissingCodecError < Error; end
class InvalidFieldError < Error; end
class InvalidPouchError < Error; end
class MissingRequiredFieldError < Error; end
class ImmutableFieldUpdateError < Error; end
class UnsupportedError < Error; end
end
|
uhoh-itsmaciek/attr_pouch
|
spec/attr_pouch_spec.rb
|
require 'spec_helper'
describe AttrPouch do
%i[hstore json jsonb].each do |storage_kind|
context "with a #{storage_kind} backing column" do
let(:column_name) { "attrs_#{storage_kind}".to_sym }
let(:storage_wrapper) do
case storage_kind
when :hstore
->(hash) { Sequel.hstore(hash) }
when :json, :jsonb
->(hash) { Sequel.pg_json(hash) }
else
raise ArgumentError, "Unknown kind, #{kind}"
end
end
def make_pouchy(field_name, opts={})
col_name = column_name
Class.new(Sequel::Model(:items)) do
include AttrPouch
pouch(col_name) do
field field_name, opts
end
end.create
end
def wrap_hash(hash)
hash = Hash[hash.map { |k,v| [ k.to_s, v ] }]
storage_wrapper.call(hash)
end
context "with a simple attribute" do
let(:pouchy) { make_pouchy(:foo, type: String) }
it "generates getter and setter" do
pouchy.foo = 'bar'
expect(pouchy.foo).to eq('bar')
end
it "clears on reload" do
pouchy.update(foo: 'bar')
expect(pouchy.foo).to eq('bar')
pouchy.foo = 'baz'
pouchy.reload
expect(pouchy.foo).to eq('bar')
end
it "marks the field as modified" do
pouchy.foo = 'bar'
result = pouchy.save_changes
expect(result).to_not be_nil
pouchy.reload
expect(pouchy.foo).to eq('bar')
end
it "does not share stores across object instances" do
pouchy1 = pouchy.class.new(foo: "bar")
pouchy2 = pouchy.class.new(foo: "baz")
pouch1_id = pouchy1[column_name].object_id
pouch2_id = pouchy2[column_name].object_id
expect(pouch1_id).not_to eq(pouch2_id)
end
it "avoids marking the field as modified if it is not changing" do
pouchy.foo = 'bar'
expect(pouchy.save_changes).to_not be_nil
pouchy.foo = 'bar'
expect(pouchy.save_changes).to be_nil
end
it "requires the attribute to be present if read" do
expect { pouchy.foo }.to raise_error(AttrPouch::MissingRequiredFieldError)
end
context "with nil values" do
let(:pouchy) { make_pouchy(:f1, type: :nil_hater) }
before do
AttrPouch.configure do |config|
config.encode(:nil_hater) { |f,v| v.nil? ? (raise ArgumentError) : v }
config.decode(:nil_hater) { |f,v| v.nil? ? (raise ArgumentError) : v }
end
end
it "bypasses encoding" do
pouchy.update(f1: 'foo')
expect { pouchy.update(f1: nil) }.not_to raise_error
expect(pouchy.f1).to be_nil
end
it "bypasses decoding" do
pouchy.update(column_name => wrap_hash(f1: nil))
expect { pouchy.f1 }.not_to raise_error
expect(pouchy.f1).to be_nil
end
it "still records the value as nil if not present when writing" do
pouchy.update(f1: nil)
expect(pouchy[column_name]).to have_key('f1')
expect(pouchy[column_name].fetch('f1')).to be_nil
end
end
end
context "with an integer attribute" do
let(:pouchy) { make_pouchy(:foo, type: Integer) }
it "preserves the type" do
pouchy.update(foo: 42)
pouchy.reload
expect(pouchy.foo).to eq(42)
end
end
context "with a float attribute" do
let(:pouchy) { make_pouchy(:foo, type: Float) }
it "preserves the type" do
pouchy.update(foo: 2.78)
pouchy.reload
expect(pouchy.foo).to eq(2.78)
end
end
context "with a boolean attribute" do
let(:pouchy) { make_pouchy(:foo, type: :bool) }
it "preserves the type" do
pouchy.update(foo: true)
pouchy.reload
expect(pouchy.foo).to be true
end
end
context "with a Time attribute" do
let(:pouchy) { make_pouchy(:foo, type: Time) }
it "preserves the type" do
now = Time.now
pouchy.update(foo: now)
pouchy.reload
expect(pouchy.foo).to eq(now)
end
end
context "with a Sequel::Model attribute" do
let(:model_class) { Class.new(Sequel::Model(:items)) }
let(:pouchy) { make_pouchy(:foo, type: model_class) }
it "preserves the type" do
new_model = model_class.create
pouchy.update(foo: new_model)
pouchy.reload
expect(pouchy.foo).to be_a(model_class)
expect(pouchy.foo.id).to eq(new_model.id)
end
end
context "with a Sequel::Model attribute provided as a String" do
let(:model_class) do
module A; class B < Sequel::Model(:items); end; end; A::B
end
let(:pouchy) { make_pouchy(:foo, type: model_class.name) }
it "preserves the type" do
new_model = model_class.create
pouchy.update(foo: new_model)
pouchy.reload
expect(pouchy.foo).to be_a(model_class)
expect(pouchy.foo.id).to eq(new_model.id)
end
end
context "with an attribute that is not a simple method name" do
it "raises an error when defining the class" do
expect do
make_pouchy(:"nope, not valid", type: String)
end.to raise_error(AttrPouch::InvalidFieldError)
end
end
context "with an attribute name that ends in a question mark" do
let(:pouchy) { make_pouchy(:foo?, type: :bool) }
it "generates normal getter" do
pouchy[column_name] = wrap_hash(foo?: true)
expect(pouchy.foo?).to be true
end
it "generates setter by stripping trailing question mark" do
pouchy.foo = true
expect(pouchy.foo?).to be true
end
end
context "with multiple attributes" do
let(:bepouched) do
col_name = column_name
Class.new(Sequel::Model(:items)) do
include AttrPouch
pouch(col_name) do
field :f1, type: String
field :f2, type: :bool
field :f3, type: Integer
end
end
end
let(:pouchy) { bepouched.create }
it "allows updating multiple attributes simultaneously" do
pouchy.update(f1: 'hello', f2: true, f3: 42)
expect(pouchy.f1).to eq('hello')
expect(pouchy.f2).to eq(true)
expect(pouchy.f3).to eq(42)
end
it "allows updating multiple attributes sequentially" do
pouchy.f1 = 'hello'
pouchy.f2 = true
pouchy.f3 = 42
pouchy.save_changes
pouchy.reload
expect(pouchy.f1).to eq('hello')
expect(pouchy.f2).to eq(true)
expect(pouchy.f3).to eq(42)
end
end
context "with the default option" do
let(:pouchy) { make_pouchy(:foo, type: String, default: 'hello') }
it "returns the default if the key is absent" do
expect(pouchy.foo).to eq('hello')
end
it "returns the value if the key is present" do
pouchy.update(foo: 'goodbye')
expect(pouchy.foo).to eq('goodbye')
end
context "with the deletable option" do
let(:pouchy) { make_pouchy(:foo, type: String,
default: 'hello',
deletable: true) }
it "it returns the default if the key is absent" do
expect(pouchy.foo).to eq('hello')
end
it "it returns the default after the field has been deleted" do
pouchy.update(foo: 'goodbye')
expect(pouchy.foo).to eq('goodbye')
pouchy.delete_foo
expect(pouchy.foo).to eq('hello')
end
end
end
context "with the deletable option" do
let(:pouchy) { make_pouchy(:foo, type: Integer, deletable: true) }
it "is nil if the field is absent" do
expect(pouchy.foo).to be_nil
end
it "supports deleting existing fields" do
pouchy.update(foo: 42)
expect(pouchy.foo).to eq(42)
pouchy.delete_foo
expect(pouchy[column_name]).not_to have_key(:foo)
pouchy.reload
expect(pouchy.foo).to eq(42)
end
it "supports deleting existing fields and immediately persisting changes" do
pouchy.update(foo: 42)
expect(pouchy.foo).to eq(42)
pouchy.delete_foo!
expect(pouchy[column_name]).not_to have_key(:foo)
pouchy.reload
expect(pouchy[column_name]).not_to have_key(:foo)
end
it "ignores deleting absent fields" do
expect(pouchy[column_name]).not_to have_key(:foo)
pouchy.delete_foo
expect(pouchy[column_name]).not_to have_key(:foo)
end
it "also deletes aliases from the was option" do
pouchy = make_pouchy(:foo, type: Integer, deletable: true, was: :bar)
pouchy.update(column_name => wrap_hash(bar: 42))
expect(pouchy.foo).to eq(42)
pouchy.delete_foo
expect(pouchy[column_name]).not_to have_key(:bar)
end
end
context "with the mutable option" do
let(:pouchy) { make_pouchy(:foo, type: Integer, mutable: false) }
it "it allows setting the field value for the first time" do
pouchy.update(foo: 42)
end
it "forbids subsequent modifications to the field" do
pouchy.update(foo: 42)
expect do
pouchy.update(foo: 43)
end.to raise_error(AttrPouch::ImmutableFieldUpdateError)
end
end
context "with the was option" do
let(:pouchy) { make_pouchy(:foo, type: String, was: %w(bar baz)) }
it "supports aliases for renaming fields" do
pouchy.update(column_name => wrap_hash(bar: 'hello'))
expect(pouchy.foo).to eq('hello')
end
it "supports multiple aliases" do
pouchy.update(column_name => wrap_hash(baz: 'hello'))
expect(pouchy.foo).to eq('hello')
end
it "deletes old names when writing the current one" do
pouchy.update(column_name => wrap_hash(bar: 'hello'))
pouchy.update(foo: 'goodbye')
expect(pouchy[column_name]).not_to have_key(:bar)
end
it "supports a shorthand for the single-alias case" do
pouchy = make_pouchy(:foo, type: String, was: :bar)
pouchy.update(column_name => wrap_hash(bar: 'hello'))
expect(pouchy.foo).to eq('hello')
end
end
context "with the raw_field option" do
let(:pouchy) { make_pouchy(:foo, type: Float, raw_field: :raw_foo) }
it "supports direct access to the encoded value" do
pouchy.update(foo: 2.78)
expect(pouchy.raw_foo).to eq('2.78')
end
it "is required when read" do
expect do
pouchy.raw_foo
end.to raise_error(AttrPouch::MissingRequiredFieldError)
end
it "avoids marking the field as modified if it is not changing" do
pouchy.raw_foo = 'bar'
expect(pouchy.save_changes).to_not be_nil
pouchy.raw_foo = 'bar'
expect(pouchy.save_changes).to be_nil
end
it "obeys the 'mutable' option" do
pouchy = make_pouchy(:foo, type: Float,
raw_field: :raw_foo,
mutable: false)
pouchy.update(foo: 42)
expect do
pouchy.update(foo: 43)
end.to raise_error(AttrPouch::ImmutableFieldUpdateError)
end
it "is nil when the 'default' option is present" do
pouchy = make_pouchy(:foo, type: Float, raw_field: :raw_foo, default: 7.2)
expect(pouchy.raw_foo).to be_nil
end
it "obeys the 'was' option when reading" do
pouchy = make_pouchy(:foo, type: String, raw_field: :raw_foo, was: :bar)
pouchy[column_name] = wrap_hash(bar: 'hello')
expect(pouchy.raw_foo).to eq('hello')
end
it "obeys the 'was' option when writing" do
pouchy = make_pouchy(:foo, type: String, raw_field: :raw_foo, was: :bar)
pouchy[column_name] = wrap_hash(bar: 'hello')
pouchy.update(raw_foo: 'goodbye')
expect(pouchy[column_name]).not_to have_key(:bar)
end
end
context "inferring field types" do
it "infers field named num_foo to be of type Integer" do
pouchy = make_pouchy(:num_foo)
pouchy.update(num_foo: 42)
expect(pouchy.num_foo).to eq(42)
end
it "infers field named foo_count to be of type Integer" do
pouchy = make_pouchy(:foo_count)
pouchy.update(foo_count: 42)
expect(pouchy.foo_count).to eq(42)
end
it "infers field named foo_size to be of type Integer" do
pouchy = make_pouchy(:foo_size)
pouchy.update(foo_size: 42)
expect(pouchy.foo_size).to eq(42)
end
it "infers field named foo? to be of type :bool" do
pouchy = make_pouchy(:foo?)
pouchy.update(foo: true)
expect(pouchy.foo?).to be true
end
it "infers field named foo_at to be of type Time" do
now = Time.now
pouchy = make_pouchy(:foo_at)
pouchy.update(foo_at: now)
expect(pouchy.foo_at).to eq(now)
end
it "infers field named foo_by to be of type Time" do
now = Time.now
pouchy = make_pouchy(:foo_by)
pouchy.update(foo_by: now)
expect(pouchy.foo_by).to eq(now)
end
it "infers field named foo to be of type String" do
pouchy = make_pouchy(:foo)
pouchy.update(foo: 'hello')
expect(pouchy.foo).to eq('hello')
end
end
context "with dataset methods" do
let(:bepouched) do
col_name = column_name
Class.new(Sequel::Model(:items)) do
include AttrPouch
pouch(col_name) do
field :f1, type: String
field :f2, type: String
field :f3, type: String
field :f4, type: :rot13
end
end
end
def rot13(str)
str.each_byte.map do |c|
case c
when 'a'.ord..('z'.ord - 13)
c + 13
when ('z'.ord - 13)..'z'.ord
c - 13
end
end.map(&:chr).join
end
before do
AttrPouch.configure do |config|
config.encode(:rot13) { |f,v| rot13(v.to_s) }
config.decode(:rot13) { |f,v| rot13(v) }
end
end
if storage_kind == :json
it "does not support dataset methods" do
pouchy = bepouched.create(f1: 'foo', f2: 'bar', f3: 'baz')
bepouched.create(f1: 'bar', f2: 'foo', f3: 'baz') # *not* matching
expect do
bepouched.where_pouch(column_name, f1: 'foo').all
end.to raise_error(::AttrPouch::UnsupportedError)
end
else
it "finds the right item with a scalar field value" do
pouchy = bepouched.create(f1: 'foo', f2: 'bar', f3: 'baz')
bepouched.create(f1: 'bar', f2: 'foo', f3: 'baz') # *not* matching
matching = bepouched.where_pouch(column_name, f1: 'foo').all
expect(matching.count).to eq(1)
match = matching.first
expect(match.id).to eq(pouchy.id)
end
it "finds the right item with an array field value" do
p1 = bepouched.create(f1: 'foo', f2: 'bar', f3: 'baz')
p2 = bepouched.create(f1: 'bar', f2: 'foo', f3: 'baz')
bepouched.create(f1: 'baz', f2: 'foo', f3: 'bar') # *not* matching
matching = bepouched.where_pouch(column_name, f1: %w(foo bar)).all
expect(matching.count).to eq(2)
expect(matching.map(&:id)).to include(p1.id, p2.id)
end
it "finds the right item with a missing field value" do
p1 = bepouched.create(f2: 'bar', f3: 'baz')
bepouched.create(f1: '', f2: 'foo', f3: 'baz') # *not* matching
bepouched.create(f1: 'baz', f2: 'foo', f3: 'bar') # *not* matching
matching = bepouched.where_pouch(column_name, f1: nil).all
expect(matching.count).to eq(1)
expect(matching.first.id).to eq(p1.id)
end
it "finds the right item with a nil field value" do
p1 = bepouched.create(column_name => wrap_hash(f1: nil))
matching = bepouched.where_pouch(column_name, f1: nil).all
expect(matching.count).to eq(1)
expect(matching.first.id).to eq(p1.id)
end
it "uses the associated encoder for lookups" do
encoded = rot13('hello')
p1 = bepouched.create(f4: 'hello')
expect(p1[column_name]['f4']).to eq(encoded) # nothing behind the curtain
matching = bepouched.where_pouch(column_name, f4: 'hello')
expect(matching.count).to eq(1)
expect(matching.first.id).to eq(p1.id)
end
context "using indexes" do
before do
bepouched.create(column_name => wrap_hash(f1: nil))
end
def plan_when_looking_for(values)
stmt = bepouched.where_pouch(column_name, f1: values).sql
db = bepouched.db
db.transaction do
db.run("SET LOCAL enable_seqscan = false")
db.fetch("EXPLAIN #{stmt}").all
end.map { |line| line.fetch(:"QUERY PLAN") }.join("\n")
end
it "uses index when looking for a single value" do
expect(plan_when_looking_for('hello')).to match(/index/i)
end
it "uses index when looking for multiple values" do
expect(plan_when_looking_for(%(hello world))).to match(/index/i)
end
xit "uses index when looking for a nil value" do
expect(plan_when_looking_for(nil)).to match(/index/i)
end
end
end
end
end
end
end
|
uhoh-itsmaciek/attr_pouch
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'bundler'
require 'attr_pouch'
conn = Sequel.connect(ENV['DATABASE_URL'])
conn.run 'CREATE EXTENSION IF NOT EXISTS "hstore"'
conn.extension :pg_hstore
conn.extension :pg_json
Sequel.extension :pg_hstore_ops
Sequel.extension :pg_json_ops
conn.run 'CREATE EXTENSION IF NOT EXISTS "hstore"'
conn.run 'DROP TABLE IF EXISTS items'
conn.run <<-EOF
CREATE TABLE items(
id serial primary key,
attrs_hstore hstore default '',
attrs_json json default '{}',
attrs_jsonb jsonb default '{}'
);
CREATE INDEX items_hstore_idx ON items USING gin (attrs_hstore);
CREATE INDEX items_jsonb_idx ON items USING gin (attrs_jsonb);
EOF
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.before(:example) do
conn.run 'TRUNCATE items'
end
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
|
as181920/rails_kindeditor_qiniu
|
lib/rails_kindeditor/engine.rb
|
require "rails_kindeditor_qiniu"
require "rails"
require "action_controller"
module RailsKindeditor
class Engine < Rails::Engine
initializer "rails_kindeditor.assets_precompile" do |app|
app.config.assets.precompile += RailsKindeditor.assets
end
initializer "rails_kindeditor.simple_form_and_formtastic" do
require "rails_kindeditor/simple_form" if Object.const_defined?("SimpleForm")
require "rails_kindeditor/formtastic" if Object.const_defined?("Formtastic")
end
initializer "rails_kindeditor.helper_and_builder" do
ActiveSupport.on_load :action_view do
ActionView::Base.send(:include, RailsKindeditor::Helper)
ActionView::Helpers::FormBuilder.send(:include, RailsKindeditor::Builder)
end
end
end
end
|
as181920/rails_kindeditor_qiniu
|
lib/generators/rails_kindeditor/migration/templates/models/mongoid/kindeditor/asset.rb
|
<filename>lib/generators/rails_kindeditor/migration/templates/models/mongoid/kindeditor/asset.rb
require 'carrierwave/mongoid'
class Kindeditor::Asset
include Mongoid::Document
include Mongoid::Timestamps
mount_uploader :asset, AssetUploader
field :file_size, :type => Integer
field :file_type, :type => String
validates_presence_of :asset
before_save :update_asset_attributes
attr_accessible :asset
def self.collection_name
:kindeditor_assets
end
private
def update_asset_attributes
self.file_size = asset.file.size
self.file_type = asset.file.content_type
end
end
|
as181920/rails_kindeditor_qiniu
|
lib/generators/rails_kindeditor/migration/migration_generator.rb
|
<filename>lib/generators/rails_kindeditor/migration/migration_generator.rb<gh_stars>1-10
module RailsKindeditor
class MigrationGenerator < Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
desc "Copy model and migration to your application."
class_option :orm, :type => :string, :aliases => "-o", :default => "active_record", :desc => "ORM options: active_record or mongoid"
def copy_files
orm = options[:orm].to_s
orm = "active_record" unless %w{active_record mongoid}.include?(orm)
%w(asset file flash image media).each do |file|
copy_model(orm, file)
end
if orm == "active_record"
migration_template "migration/migration.rb", "db/migrate/create_kindeditor_assets.rb"
end
end
def self.next_migration_number(dirname)
if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.3d" % (current_migration_number(dirname) + 1)
end
end
private
def copy_model(orm, name)
template "models/#{orm}/kindeditor/#{name}.rb", "app/models/kindeditor/#{name}.rb"
end
end
end
|
as181920/rails_kindeditor_qiniu
|
rails_kindeditor_qiniu.gemspec
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "rails_kindeditor/version"
Gem::Specification.new do |s|
s.name = "rails_kindeditor_qiniu"
s.version = RailsKindeditor::VERSION
s.platform = Gem::Platform::RUBY
s.authors = "Macrow"
s.email = "<EMAIL>"
s.homepage = "https://github.com/as181920/rails_kindeditor_qiniu"
s.summary = "Kindeditor sotres file in qiniu"
s.description = "rails_kindeditor will helps your rails app integrate with kindeditor, including images and files uploading."
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
end
|
as181920/rails_kindeditor_qiniu
|
app/controllers/kindeditor/assets_controller.rb
|
<filename>app/controllers/kindeditor/assets_controller.rb<gh_stars>1-10
# encoding: utf-8
class Kindeditor::AssetsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
@img_file = params[:imgFile]
upload_token = generate_upload_token
key = generate_key
bucket = QINIU_CONFIG["bucket"]
response = Qiniu::RS.upload_file \
uptoken: upload_token,
file: @img_file.tempfile.path,
bucket: bucket,
key: key,
note: "rails kindeditor"
Kindeditor::Asset.create \
asset: key,
file_name: @img_file.original_filename,
file_type: @img_file.content_type,
file_size: @img_file.size
p response # should be checked for error handle
render :text => ({:error => 0, :url => "http://#{bucket}.qiniudn.com/#{key}"}.to_json)
end
private
def generate_upload_token
Qiniu::RS.generate_upload_token \
scope: QINIU_CONFIG["bucket"],
customer: "rails_kindeditor"
end
def generate_key
SecureRandom.uuid
end
end
|
as181920/rails_kindeditor_qiniu
|
lib/generators/rails_kindeditor/migration/templates/models/active_record/kindeditor/asset.rb
|
<filename>lib/generators/rails_kindeditor/migration/templates/models/active_record/kindeditor/asset.rb<gh_stars>1-10
class Kindeditor::Asset < ActiveRecord::Base
self.table_name = 'kindeditor_assets'
attr_accessible :asset, :file_name, :file_type, :file_size
#mount_uploader :asset, AssetUploader
#validates_presence_of :asset
#before_save :update_asset_attributes
#
#private
#def update_asset_attributes
# self.file_size = asset.file.size
# self.file_type = asset.file.content_type
#end
end
|
as181920/rails_kindeditor_qiniu
|
lib/rails_kindeditor/helper.rb
|
<reponame>as181920/rails_kindeditor_qiniu<filename>lib/rails_kindeditor/helper.rb
module RailsKindeditor
module Helper
def kindeditor_tag(name, content = nil, options = {})
id = sanitize_to_id(name)
input_html = { :id => id }.merge(options.delete(:input_html) || {})
output = ActiveSupport::SafeBuffer.new
output << text_area_tag(name, content, input_html)
output << javascript_tag(js_replace(id, options))
end
def kindeditor(name, method, options = {})
input_html = (options.delete(:input_html) || {})
hash = input_html.stringify_keys
instance_tag = ActionView::Base::InstanceTag.new(name, method, self, options.delete(:object))
instance_tag.send(:add_default_name_and_id, hash)
output_buffer = ActiveSupport::SafeBuffer.new
output_buffer << instance_tag.to_text_area_tag(input_html)
js = js_replace(hash['id'], options)
output_buffer << javascript_tag(js)
end
private
def js_replace(dom_id, options = {})
"KindEditor.ready(function(K){
K.create('##{dom_id}', #{get_options(options).to_json});
});"
end
def get_options(options)
options.delete(:uploadJson)
options.delete(:fileManagerJson)
options.reverse_merge!(:width => '100%')
options.reverse_merge!(:height => 300)
options.reverse_merge!(:allowFileManager => true)
options.merge!(:uploadJson => '/kindeditor/upload')
options.merge!(:fileManagerJson => '/kindeditor/filemanager')
if options[:simple_mode] == true
options.delete(:simple_mode)
options.merge!(:items => %w{fontname fontsize | forecolor hilitecolor bold italic underline removeformat | justifyleft justifycenter justifyright insertorderedlist insertunorderedlist | emoticons image link})
end
options
end
end
module Builder
def kindeditor(method, options = {})
@template.send("kindeditor", @object_name, method, objectify_options(options))
end
end
end
|
indykish/knife-google
|
lib/chef/knife/google_base.rb
|
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'chef/knife'
require 'google/compute'
class Chef
class Knife
module GoogleBase
# hack for mixlib-cli workaround
# https://github.com/opscode/knife-ec2/blob/master/lib/chef/knife/ec2_base.rb
def self.included(includer)
includer.class_eval do
deps do
require 'google/compute'
require 'chef/json_compat'
end
option :compute_credential_file,
:short => "-f CREDENTIAL_FILE",
:long => "--gce-credential-file CREDENTIAL_FILE",
:description => "Google Compute credential file (google setup can create this)"
end
end
def client
@client ||= begin
Google::Compute::Client.from_json(config[:compute_credential_file])
end
end
def selflink2name(selflink)
selflink.to_s == '' ? selflink.to_s : selflink.split('/').last
end
def msg_pair(label, value, color=:cyan)
if value && !value.to_s.empty?
ui.info("#{ui.color(label, color)}: #{value}")
end
end
def disks(instance)
instance.disks.collect{|d|d.device_name}.compact
end
def private_ips(instance)
instance.network_interfaces.collect{|ni|ni.network_ip}.compact
end
def public_ips(instance)
instance.network_interfaces.collect{|ni|
ni.access_configs.map{|ac|
ac.nat_ip
}
}.flatten.compact
end
end
end
end
|
indykish/knife-google
|
lib/google/compute/client.rb
|
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/api_client'
require 'multi_json'
require 'google/compute/resource_collection'
require 'knife-google/version'
module Google
module Compute
class Client
DEFAULT_FILE = '~/.google-compute.json'
attr_reader :dispatcher
def initialize(authorization, project, credential_file)
api_client = Google::APIClient.new(:application_name => 'knife-google', :application_version => Knife::Google::VERSION)
api_client.authorization = authorization
api_client.auto_refresh_token = true
@project = project
@credential_file = credential_file
@dispatcher = APIDispatcher.new(:project=>project,:api_client=>api_client)
end
def self.from_json(filename = nil)
filename ||= File.expand_path(DEFAULT_FILE)
begin
credential_data = MultiJson.load(File.read(filename))
rescue
$stdout.print "Error reading CREDENTIAL_FILE, please run 'knife google setup'\n"
exit 1
end
authorization = Signet::OAuth2::Client.new(credential_data)
self.new(authorization, credential_data['project'], filename)
end
def self.setup
$stdout.print "Enter project ID (not name or number): "
project = $stdin.gets.chomp
$stdout.print "Enter client id: "
client_id = $stdin.gets.chomp
$stdout.print "Enter client secret: "
client_secret = $stdin.gets.chomp
authorization_uri = "https://accounts.google.com/o/oauth2/auth"
token_credential_uri ="https://accounts.google.com/o/oauth2/token"
scope = ["https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/devstorage.read_write",
"https://www.googleapis.com/auth/devstorage.write_only",
"https://www.googleapis.com/auth/userinfo.email"]
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
api_client = Google::APIClient.new(:application_name => 'knife-google', :application_version => Knife::Google::VERSION)
api_client.authorization.scope = scope
api_client.authorization.client_id = client_id
api_client.authorization.client_secret = client_secret
api_client.authorization.redirect_uri = redirect_uri
$stdout.puts "Copy and paste the following url in your brower and allow access. Enter the resulting authorization code below.\n\n"
$stdout.puts api_client.authorization.authorization_uri
$stdout.print "\n\nAuthorization code: "
authorization_code = $stdin.gets.chomp
api_client.authorization.code = authorization_code
begin
api_client.authorization.fetch_access_token!
rescue Faraday::Error::ConnectionFailed => e
raise ConnectionFail,
"The SSL certificates validation may not configured for this system. Please refer README to configured SSL certificates validation"\
if e.message.include? "SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed"
else
access_token = api_client.authorization.access_token
refresh_token = api_client.authorization.refresh_token
id_token = api_client.authorization.id_token
expires_in = api_client.authorization.expires_in
issued_at = api_client.authorization.issued_at.to_s
if !@credential_file
filepath = File.expand_path(DEFAULT_FILE)
else
filepath = File.expand_path(@credential_file)
end
File.open(filepath,'w+') do |f|
f.write(MultiJson.dump({"authorization_uri" => authorization_uri,
"token_credential_uri"=>"https://accounts.google.com/o/oauth2/token",
"scope"=>scope,"redirect_uri"=>redirect_uri, "client_id"=>client_id,
"client_secret"=>client_secret, "access_token"=>access_token,
"expires_in"=>expires_in,"refresh_token"=> refresh_token, "id_token"=>id_token,
"issued_at"=>issued_at,"project"=>project }, :pretty=>true))
end
end
end
def projects
ResourceCollection.new(:resource_class => Google::Compute::Project, :dispatcher => @dispatcher)
end
def disks
CreatableResourceCollection.new(:resource_class => Google::Compute::Disk, :dispatcher=>@dispatcher)
end
def firewalls
CreatableResourceCollection.new(:resource_class => Google::Compute::Firewall, :dispatcher => @dispatcher)
end
def images
CreatableResourceCollection.new(:resource_class => Google::Compute::Image, :dispatcher => @dispatcher)
end
def instances
CreatableResourceCollection.new(:resource_class => Google::Compute::Server, :dispatcher=>@dispatcher)
end
def machine_types
ListableResourceCollection.new(:resource_class => Google::Compute::MachineType,:dispatcher=>@dispatcher)
end
def networks
CreatableResourceCollection.new(:resource_class => Google::Compute::Network, :dispatcher=>@dispatcher)
end
def globalOperations
DeletableResourceCollection.new(:resource_class => Google::Compute::GlobalOperation, :dispatcher=>@dispatcher)
end
def regionOperations
DeletableResourceCollection.new(:resource_class => Google::Compute::RegionOperation, :dispatcher=>@dispatcher)
end
def zoneOperations
DeletableResourceCollection.new(:resource_class => Google::Compute::ZoneOperation, :dispatcher=>@dispatcher)
end
def regions
ListableResourceCollection.new(:resource_class => Google::Compute::Region, :dispatcher=>@dispatcher)
end
def zones
ListableResourceCollection.new(:resource_class => Google::Compute::Zone, :dispatcher=>@dispatcher)
end
def snapshots
CreatableResourceCollection.new(:resource_class => Google::Compute::Snapshot, :dispatcher=>@dispatcher)
end
class APIDispatcher
attr_reader :project, :api_client
def initialize(opts)
@project= opts[:project]
@api_client = opts[:api_client]
end
def compute
@compute ||= @api_client.discovered_api('compute','v1')
end
def dispatch(opts)
begin
unless opts[:parameters].has_key?(:project)
opts[:parameters].merge!( :project => @project )
end
result = @api_client.execute(:api_method=>opts[:api_method],
:parameters=>opts[:parameters],
:body_object => opts[:body_object]
)
unless result.success?
response = MultiJson.load(result.response.body)
error_code = response["error"]["code"]
if error_code == 404
raise ResourceNotFound, result.response.body
elsif error_code == 400
raise BadRequest, result.response.body
else
raise BadRequest, result.response.body
end
end
return MultiJson.load(result.response.body) unless result.response.body.nil?
rescue ArgumentError => e
raise ParameterValidation, e.message
end
end
end
end
end
end
|
belubelu/checkexploitation
|
assets/bootstrap/octicons-master/octicons-master/lib/octicons_helper/lib/octicons_helper/version.rb
|
<filename>assets/bootstrap/octicons-master/octicons-master/lib/octicons_helper/lib/octicons_helper/version.rb
module OcticonsHelper
VERSION = "8.1.3".freeze
end
|
belubelu/checkexploitation
|
assets/bootstrap/octicons-master/octicons-master/lib/octicons_gem/lib/octicons/version.rb
|
module Octicons
VERSION = "8.1.3".freeze
end
|
wafuwafu13/action-rubocop
|
test/rdjson_formatter/testdata/not_correctable_offenses.rb
|
# frozen_string_literal: true
class MyClass < Object
def no_calc(a, b)
c = a + b
a
end
end
|
wafuwafu13/action-rubocop
|
test/rdjson_formatter/testdata/correctable_offenses.rb
|
def add(xyz,abc)
a = xyz+ abc;
return a
end
|
wafuwafu13/action-rubocop
|
rdjson_formatter/rdjson_formatter.rb
|
# frozen_string_literal: true
# https://docs.rubocop.org/rubocop/formatters.html
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
class RdjsonFormatter < RuboCop::Formatter::BaseFormatter
def started(_target_files)
@rdjson = {
source: {
name: 'rubocop',
url: 'https://rubocop.org/'
},
diagnostics: []
}
super
end
def file_finished(file, offenses)
offenses.each do |offense|
next if offense.location == RuboCop::Cop::Offense::NO_LOCATION
@rdjson[:diagnostics] << build_diagnostic(file, offense)
end
end
def finished(_inspected_files)
puts @rdjson.to_json
end
private
# @param [String] file
# @param [RuboCop::Cop::Offense] offense
# @return [Hash]
def build_diagnostic(file, offense)
code, message = offense.message.split(':', 2).map(&:strip)
diagnostic = {
message: message,
location: {
path: convert_path(file),
range: {
start: {
line: offense.location.begin.line,
column: offense.location.begin.column + 1
},
end: {
line: offense.location.end.line,
column: offense.location.end.column + 1
}
}
},
severity: convert_severity(offense.severity),
code: {
value: code
},
original_output: offense.to_s
}
diagnostic[:suggestions] = build_suggestions(offense) if offense.corrector
diagnostic
end
# @param [RuboCop::Cop::Offense] offense
# @return [Array{Hash}]
def build_suggestions(offense)
range, text = offense.corrector.as_replacements[0]
[
{
range: {
start: {
line: range.begin.line,
column: range.begin.column + 1 # rubocop is 0-origin, reviewdog is 1-origin
},
end: {
line: range.end.line,
column: range.end.column + 1
}
},
text: text
}
]
end
# https://github.com/reviewdog/reviewdog/blob/1d8f6d6897dcfa67c33a2ccdc2ea23a8cca96c8c/proto/rdf/reviewdog.proto
# https://docs.rubocop.org/rubocop/configuration.html#severity
#
# @param [Symbol] severity
# @return [String]
def convert_severity(severity)
case severity
when :info
'INFO'
when :warning
'WARNING'
when :error
'ERROR'
else
'UNKNOWN_SEVERITY'
end
end
# extract reasonable relative path from (ideally) the project root.
# if `path` is `"/path/to/project/lib/my_file.rb"`,
# it generates `"lib/my_file.rb"` as
#
# ref: rubocop approach
# https://github.com/rubocop/rubocop/blob/1e55b1aa5e4c5eaeccad5d61f08b7930ed6bc341/lib/rubocop/path_util.rb#L25
#
# @param [String] path
# @return [String]
def convert_path(path)
base_path = Dir.pwd
begin
Pathname.new(File.expand_path(path)).relative_path_from(base_path).to_s
rescue ArgumentError
path
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
|
CrowdFlower/ruby-kafka
|
spec/functional/transactional_producer_spec.rb
|
# frozen_string_literal: true
describe "Transactional producer", functional: true do
example 'Typical transactional production' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.deliver_messages
producer.produce('Test 3', topic: topic, partition: 0)
producer.produce('Test 4', topic: topic, partition: 1)
producer.produce('Test 5', topic: topic, partition: 2)
producer.deliver_messages
producer.commit_transaction
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest)
expect(records.length).to eql(2)
expect(records[0].value).to eql('Test 1')
expect(records[1].value).to eql('Test 3')
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest)
expect(records.length).to eql(2)
expect(records[0].value).to eql('Test 2')
expect(records[1].value).to eql('Test 4')
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 5')
producer.shutdown
end
example 'Multiple transactional production' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.deliver_messages
producer.commit_transaction
sleep 1
producer.begin_transaction
producer.produce('Test 3', topic: topic, partition: 0)
producer.produce('Test 4', topic: topic, partition: 1)
producer.produce('Test 5', topic: topic, partition: 2)
producer.deliver_messages
producer.commit_transaction
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest)
expect(records.length).to eql(2)
expect(records[0].value).to eql('Test 1')
expect(records[1].value).to eql('Test 3')
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest)
expect(records.length).to eql(2)
expect(records[0].value).to eql('Test 2')
expect(records[1].value).to eql('Test 4')
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 5')
producer.shutdown
end
example 'Consumer could not read not-completed transactional production' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.produce('Test 3', topic: topic, partition: 2)
producer.deliver_messages
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
producer.commit_transaction
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 1')
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 2')
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 3')
producer.shutdown
end
example 'Multi-topic transaction' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic_1 = create_random_topic(num_partitions: 3)
topic_2 = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic_1, partition: 0)
producer.produce('Test 2', topic: topic_1, partition: 1)
producer.deliver_messages
producer.produce('Test 3', topic: topic_2, partition: 0)
producer.produce('Test 4', topic: topic_2, partition: 1)
producer.produce('Test 5', topic: topic_2, partition: 2)
producer.deliver_messages
producer.commit_transaction
records = kafka.fetch_messages(topic: topic_1, partition: 0, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 1')
records = kafka.fetch_messages(topic: topic_1, partition: 1, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 2')
records = kafka.fetch_messages(topic: topic_2, partition: 0, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 3')
records = kafka.fetch_messages(topic: topic_2, partition: 1, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 4')
records = kafka.fetch_messages(topic: topic_2, partition: 2, offset: :earliest)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 5')
producer.shutdown
end
example 'Consumer could not read aborted transactional production' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.produce('Test 3', topic: topic, partition: 2)
producer.deliver_messages
producer.abort_transaction
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
producer.shutdown
end
example 'Multi-topic aborted transactions' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic_1 = create_random_topic(num_partitions: 3)
topic_2 = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic_1, partition: 0)
producer.produce('Test 2', topic: topic_1, partition: 1)
producer.deliver_messages
producer.produce('Test 3', topic: topic_2, partition: 0)
producer.produce('Test 4', topic: topic_2, partition: 1)
producer.produce('Test 5', topic: topic_2, partition: 2)
producer.deliver_messages
producer.abort_transaction
records = kafka.fetch_messages(topic: topic_1, partition: 0, offset: :earliest)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic_1, partition: 1, offset: :earliest)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic_2, partition: 0, offset: :earliest)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic_2, partition: 1, offset: :earliest)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic_2, partition: 2, offset: :earliest)
expect(records.length).to eql(0)
producer.shutdown
end
example 'Fenced-out producer' do
transactional_id = SecureRandom.uuid
topic = create_random_topic(num_partitions: 3)
producer_1 = kafka.producer(
transactional: true,
transactional_id: transactional_id
)
producer_1.init_transactions
producer_1.begin_transaction
producer_1.produce('Test 1', topic: topic, partition: 0)
producer_1.produce('Test 2', topic: topic, partition: 1)
producer_1.produce('Test 3', topic: topic, partition: 2)
producer_1.deliver_messages
producer_1.commit_transaction
sleep 1
producer_2 = kafka.producer(
transactional: true,
transactional_id: transactional_id
)
producer_2.init_transactions
producer_2.begin_transaction
producer_2.produce('Test 4', topic: topic, partition: 0)
producer_2.produce('Test 5', topic: topic, partition: 1)
producer_2.deliver_messages
producer_2.commit_transaction
producer_1.begin_transaction
producer_1.produce('Test 6', topic: topic, partition: 0)
expect do
producer_1.deliver_messages
end.to raise_error(Kafka::InvalidProducerEpochError)
producer_1.shutdown
producer_2.shutdown
end
example 'Concurrent transaction' do
transactional_id = SecureRandom.uuid
topic = create_random_topic(num_partitions: 3)
producer_1 = kafka.producer(
transactional: true,
transactional_id: transactional_id
)
producer_1.init_transactions
producer_1.begin_transaction
producer_1.produce('Test 1', topic: topic, partition: 0)
producer_1.produce('Test 2', topic: topic, partition: 1)
producer_1.produce('Test 3', topic: topic, partition: 2)
producer_1.deliver_messages
# Producer 2 starts with the same transactional id to cause the concurrent transactions error
producer_2 = kafka.producer(
transactional: true,
transactional_id: transactional_id
)
producer_2.init_transactions
producer_2.begin_transaction
producer_2.produce('Test 3', topic: topic, partition: 2)
producer_2.deliver_messages
producer_2.commit_transaction
begin
producer_1.shutdown
producer_2.shutdown
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
rescue; end
end
example '#transaction syntax' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.transaction do
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.deliver_messages
producer.produce('Test 3', topic: topic, partition: 2)
producer.deliver_messages
end
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 1')
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 2')
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(1)
expect(records[0].value).to eql('Test 3')
producer.shutdown
end
example '#transaction syntax, block raises error' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
expect do
producer.transaction do
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.produce('Test 3', topic: topic, partition: 2)
producer.deliver_messages
raise 'Something went wrong'
end
end.to raise_error(/something went wrong/i)
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
producer.shutdown
end
example '#transaction syntax, block actively aborts the transaction' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
expect do
producer.transaction do
producer.produce('Test 1', topic: topic, partition: 0)
producer.produce('Test 2', topic: topic, partition: 1)
producer.produce('Test 3', topic: topic, partition: 2)
producer.deliver_messages
raise Kafka::Producer::AbortTransaction
end
end.not_to raise_error
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 1, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
records = kafka.fetch_messages(topic: topic, partition: 2, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(0)
producer.shutdown
end
example 'Transaction is idempotent by default' do
producer = kafka.producer(
transactional: true,
transactional_id: SecureRandom.uuid
)
topic = create_random_topic(num_partitions: 3)
producer.init_transactions
producer.begin_transaction
producer.produce('Test 1', topic: topic, partition: 0)
producer.deliver_messages
producer.produce('Test 2', topic: topic, partition: 0)
begin
allow_any_instance_of(Kafka::SocketWithTimeout).to receive(:read).and_raise(Errno::ETIMEDOUT)
producer.deliver_messages
rescue
end
allow_any_instance_of(Kafka::SocketWithTimeout).to receive(:read).and_call_original
producer.deliver_messages
producer.commit_transaction
records = kafka.fetch_messages(topic: topic, partition: 0, offset: :earliest, max_wait_time: 1)
expect(records.length).to eql(2)
expect(records[0].value).to eql('Test 1')
expect(records[1].value).to eql('Test 2')
producer.shutdown
end
end
|
OwnYourData/app-docs_base
|
config/routes.rb
|
Rails.application.routes.draw do
scope "(:locale)", :locale => /en|de/ do
root 'pages#index'
match 'favicon', to: 'pages#favicon', via: 'get'
end
get "/datavault" => redirect("/datavault/")
get "/notary" => redirect("/notary/")
get "/notary-sovrin" => redirect("/notary-sovrin/")
get "/semcon" => redirect("/semcon/")
get "/semcon-billing" => redirect("/semcon-billing/")
get "/semcon-validation" => redirect("/semcon-validation/")
end
|
OwnYourData/app-docs_base
|
app/controllers/pages_controller.rb
|
<filename>app/controllers/pages_controller.rb
class PagesController < ApplicationController
include ApplicationHelper
def index
end
def favicon
send_file 'public/favicon.ico', type: 'image/x-icon', disposition: 'inline'
end
end
|
OwnYourData/app-docs_base
|
config.ru
|
<filename>config.ru
# This file is used by Rack-based servers to start the application.
require_relative 'config/environment'
use Rack::ReverseProxy do
reverse_proxy(/^\/datavault(\/.*)$/, 'https://datavault-doc.ownyourdata.eu$1', opts = {:preserve_host => true})
reverse_proxy(/^\/notary(\/.*)$/, 'https://blockchain-doc.ownyourdata.eu$1', opts = {:preserve_host => true})
reverse_proxy(/^\/notary-sovrin(\/.*)$/, 'https://sovrin-doc.ownyourdata.eu$1', opts = {:preserve_host => true})
reverse_proxy(/^\/semcon(\/.*)$/, 'https://semcon-doc.ownyourdata.eu$1', opts = {:preserve_host => true})
reverse_proxy(/^\/semcon-billing(\/.*)$/, 'https://billing-doc.ownyourdata.eu$1', opts = {:preserve_host => true})
reverse_proxy(/^\/semcon-validation(\/.*)$/, 'https://validation-doc.ownyourdata.eu$1', opts = {:preserve_host => true})
end
use Rack::Deflater
run Rails.application
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/alarms/alarm_resource_spec.rb
|
require 'spec_helper'
describe AlarmResource do
let(:prefix) { 'ec2-hoge' }
let(:response) do
{
alarm_name: 'ec2-hoge-moge'
}
end
let(:stub_responses) do
{ describe_alarms: { metric_alarms: [ response ] } }
end
let(:cloudwatch) { Aws::CloudWatch::Client.new(stub_responses: stub_responses) }
let(:target) { described_class.new(cloudwatch) }
describe 'alarm' do
subject { target.alarm(AlarmDefinition.new({alarm_name: 'hoge'})) }
it { is_expected.to be_instance_of Alarm }
end
describe 'find_by_name_prefix' do
subject { target.find_by_name_prefix(prefix) }
it do
is_expected.to be_instance_of Aws::CloudWatch::Alarm::Collection
expect(subject.first.name).to eq 'ec2-hoge-moge'
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/alarms/alarm_resource.rb
|
class AlarmResource
# @param [Aws::CloudWatch::Client] cloudwatch
def initialize(cloudwatch)
@cloudwatch = Aws::CloudWatch::Resource.new(client: cloudwatch)
end
# @param [AlarmDefinition] definition
# @return [Alarm]
def alarm(definition)
Alarm.new(definition, @cloudwatch)
end
def alarms
@cloudwatch.alarms
end
def find_by_name_prefix(prefix)
@cloudwatch.alarms(alarm_name_prefix: prefix)
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/definitions/alarm_definition_repository_spec.rb
|
<reponame>QLife-Inc/ec2-auto-metric-alarms<filename>spec/libs/definitions/alarm_definition_repository_spec.rb
require 'spec_helper'
require 'stringio'
describe AlarmDefinitionRepository do
let(:bucket_name) { 'test_bucket' }
let(:prefix) { 'definitions/' }
let(:response) do
{
head_object: { content_length: 1 },
get_object: { body: StringIO.new('hoge') }
}
end
let(:client) { Aws::S3::Client.new(stub_responses: response) }
let(:target) { described_class.new(client) }
before do
ENV['DEFINITION_BUCKET_NAME'] = bucket_name
ENV['DEFINITION_OBJECT_PREFIX'] = prefix
end
describe 'initialize' do
describe 'bucket' do
subject { target.instance_variable_get(:@bucket).name }
it { is_expected.to eq bucket_name }
end
describe 'prefix' do
subject { target.instance_variable_get(:@prefix) }
it { is_expected.to eq prefix }
end
end
describe 'get_alarm_definition' do
let(:definition_name) { 'test.json' }
subject { target.get_alarm_definition(definition_name).body }
it { is_expected.to eq 'hoge' }
context 'when object is missing' do
let(:response) { { head_object: nil } }
it { is_expected.to eq '{"error":"s3://test_bucket/definitions/test.json is not found."}' }
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/definitions/alarm_definitions_spec.rb
|
require 'spec_helper'
describe AlarmDefinitions do
let(:empty_definition) do
File.read(File.expand_path('./nesting-definitions.json', __dir__))
end
let(:cpu_util_json) do
File.read(File.expand_path('./cpu-util.json', __dir__))
end
let(:target_json) { cpu_util_json }
let(:target) { described_class.new(JSON.parse(target_json, symbolize_names: true)) }
describe 'initialize' do
it { expect(target.include_definitions).to be_empty }
it { expect(target.definitions.size).to be 2 }
end
describe 'empty?' do
let(:target_json) { empty_definition }
it { expect(target).to be_empty }
end
describe 'add_definition' do
let(:alarm_id) { 'additional-alarm-id' }
let(:additional) do
AlarmDefinition.new(alarm_id: alarm_id)
end
before { target.add_definition(additional) }
context 'when alarm_id not exists' do
it { expect(target.definitions.size).to be 3 }
end
context 'when alarm_id already exists' do
let(:alarm_id) { 'emergency-cpu-util' }
it { expect(target.definitions.size).to be 2 }
end
end
describe 'remove_ignore_alarms' do
let(:ignore_alarm_id) { 'emergency-cpu-util' }
before do
target.instance_variable_set(:@ignore_alarm_ids, [ignore_alarm_id])
target.remove_ignore_alarms
end
subject { target.definitions }
it { expect(subject.size).to be 1 }
it { expect(subject.find { |d| d.alarm_id == ignore_alarm_id}).to be_nil }
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/alarms/alarm_spec.rb
|
<filename>spec/libs/alarms/alarm_spec.rb<gh_stars>1-10
require 'spec_helper'
describe Alarm do
let(:alarm_id) { 'alarm_id' }
let(:notification_type) { AlarmDefinition::NOTIFICATION_TYPE_EMERGENCY }
let(:definition) do
{
alarm_id: alarm_id,
notification_type: notification_type,
alarm_name: 'test-alarm',
namespace: 'AWS/EC2',
dimensions: [{ name: "InstanceId", value: "instance-id" }],
}
end
let(:alarm_definition) { AlarmDefinition.new(definition) }
let(:metric_alarm) do
{
alarm_name: 'test-alarm',
namespace: 'AWS/EC2',
dimensions: [{ name: "InstanceId", value: "instance-id" }],
}
end
let(:client) do
client = instance_double('Aws::CloudWatch::Client')
allow(client).to receive(:put_metric_alarm).and_return(metric_alarm)
client
end
let(:alarm) do
alarm = instance_double('Aws::CloudWatch::Alarm')
allow(alarm).to receive(:exists?).and_return(true)
allow(alarm).to receive(:delete)
alarm
end
let(:cloudwatch) do
resource = instance_double('Aws::CloudWatch::Resource')
allow(resource).to receive(:client).and_return(client)
allow(resource).to receive(:alarm).with(definition[:alarm_name]).and_return(alarm)
resource
end
let(:target) { described_class.new(alarm_definition, cloudwatch) }
let(:actions) do
{
alarm_actions: [Settings.emergency_topic_arn],
ok_actions: [Settings.emergency_topic_arn],
}
end
describe 'delete' do
before { target.delete }
subject { alarm }
it { is_expected.to have_received(:delete).once }
end
describe 'create' do
before { target.create }
it do
expect(client).to have_received(:put_metric_alarm)
.with(metric_alarm.merge(actions)).once
end
context 'when ordinary' do
let(:notification_type) { AlarmDefinition::NOTIFICATION_TYPE_ORDINARY }
let(:actions) do
{
alarm_actions: [Settings.ordinary_topic_arn],
ok_actions: [Settings.ordinary_topic_arn],
}
end
it do
expect(client).to have_received(:put_metric_alarm)
.with(metric_alarm.merge(actions)).once
end
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/auto_alarm_facade_factory_spec.rb
|
require 'spec_helper'
describe AutoAlarmFacadeFactory do
let!(:ec2) { Aws::EC2::Resource.new(client: Aws::EC2::Client.new(stub_responses: true)) }
let!(:s3) { Aws::S3::Client.new(stub_responses: true) }
let!(:cw) { Aws::CloudWatch::Client.new(stub_responses: true) }
describe 'create' do
let!(:facade) { described_class.create(ec2, s3, cw) }
it { expect(facade).to be_instance_of AutoAlarmFacade }
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/definitions/alarm_definition_resolver_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
class AlarmDefinitionRepositoryMock
def get_alarm_definition(alarm_definition_name)
body = File.read(File.expand_path(alarm_definition_name, __dir__))
content_type = alarm_definition_name.end_with?('json') ? 'text/json' : 'text/yaml'
mock_object = OpenStruct.new(get: OpenStruct.new(body: OpenStruct.new(read: body)), content_type: content_type)
AlarmDefinitionTemplate.new(mock_object)
end
end
describe AlarmDefinitionResolver do
let(:alarm_definition_name) { 'cpu-util.json' }
let(:instance_id) { 'i-12345' }
let(:instance_name) { 'aInstance' }
let(:tags) do
[
OpenStruct.new(key: 'Name', value: instance_name),
OpenStruct.new(key: 'DefName', value: alarm_definition_name),
]
end
let(:instance) do
Aws::EC2::Instance.new(id: instance_id, data: { tags: tags })
end
let(:target) { described_class.new(AlarmDefinitionRepositoryMock.new) }
before do
Settings.instance_variable_set(:@definition_tag_key, nil)
ENV['DEFINITION_TAG_KEY'] = 'DefName'
end
describe 'resolve' do
let(:results) { target.resolve(instance) }
context 'when simple definition' do
it do
expect(results.size).to be 2
# @type [AlarmDefinition] emergency
emergency = results.find {|d| d.notification_type == AlarmDefinition::NOTIFICATION_TYPE_EMERGENCY}
expect(emergency.definition[:alarm_name]).to eq "ec2-#{instance_id}-emergency-cpu-util"
expect(emergency.definition[:alarm_description]).to eq "#{instance_name} CPU使用率が 30 分間 90 % を超えていたら通知"
# @type [AlarmDefinition] ordinary
ordinary = results.find {|d| d.notification_type == AlarmDefinition::NOTIFICATION_TYPE_ORDINARY}
expect(ordinary.definition.dig(:dimensions)&.first[:value]).to eq instance_id
end
end
context 'when simple definition of yaml' do
let(:alarm_definition_name) { 'cpu-util.yml' }
it do
expect(results.size).to be 2
# @type [AlarmDefinition] emergency
emergency = results.find {|d| d.notification_type == AlarmDefinition::NOTIFICATION_TYPE_EMERGENCY}
expect(emergency.definition[:alarm_name]).to eq "ec2-#{instance_id}-emergency-cpu-util"
expect(emergency.definition[:alarm_description]).to eq "#{instance_name} CPU使用率が 30 分間 90 % を超えていたら通知"
# @type [AlarmDefinition] ordinary
ordinary = results.find {|d| d.notification_type == AlarmDefinition::NOTIFICATION_TYPE_ORDINARY}
expect(ordinary.definition.dig(:dimensions)&.first[:value]).to eq instance_id
end
end
context 'when nested definition' do
let(:alarm_definition_name) { 'nesting-definitions.json' }
it do
expect(results.size).to be 1
# @type [AlarmDefinition] emergency
emergency = results.find {|d| d.notification_type == AlarmDefinition::NOTIFICATION_TYPE_EMERGENCY}
expect(emergency).to be_nil
# @type [AlarmDefinition] ordinary
ordinary = results.find {|d| d.notification_type == AlarmDefinition::NOTIFICATION_TYPE_ORDINARY}
expect(ordinary.definition.dig(:dimensions)&.first[:value]).to eq instance_id
end
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/definitions/instance_wrapper_spec.rb
|
<reponame>QLife-Inc/ec2-auto-metric-alarms<gh_stars>1-10
require 'spec_helper'
describe InstanceWrapper do
let(:instance_id) { 'i-0123456789' }
let(:name) { nil }
let(:alarm_definition_name) { nil }
let(:tags) do
tags = []
tags << OpenStruct.new(key: 'Name', value: name) unless name.nil?
unless alarm_definition_name.nil?
tags << OpenStruct.new(key: 'AlarmDefinitionName',
value: alarm_definition_name)
end
tags
end
let(:instance) do
Aws::EC2::Instance.new(id: instance_id, data: { tags: tags, image_id: 'ami-12345' })
end
let(:target) { described_class.new(instance) }
describe 'initialize' do
let(:wrapper) { described_class.new('hoge') }
subject { wrapper.instance_variable_get(:@instance) }
it { is_expected.to eq 'hoge' }
end
describe 'tag_value' do
let(:tag_key) { 'HogeKey' }
let(:tag_value) { 'HogeHoge' }
let(:default_value) { 'default_value' }
let(:tags) { [ OpenStruct.new(key: tag_key, value: tag_value) ] }
subject { target.tag_value(tag_key, default_value) }
context 'when has tag key' do
it { is_expected.to eq tag_value }
end
context 'when tag is missing' do
let(:tags) { [] }
it { is_expected.to eq default_value }
end
end
describe 'name' do
let(:name) { 'HogeInstance' }
subject { target.name }
it { is_expected.to eq name }
end
describe 'alarm_definition' do
let(:alarm_definition_name) { 'hoge-hoge' }
before do
Settings.instance_variable_set(:@definition_tag_key, 'AlarmDefinitionName')
end
subject { target.alarm_definition }
it { is_expected.to eq alarm_definition_name }
end
describe 'method_missing' do
context 'when instance has method' do
it { expect(target.image_id).to eq 'ami-12345' }
end
context 'when instance not have method' do
subject { -> { target.hoge } }
it { is_expected.to raise_error(NoMethodError) }
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/definitions/alarm_definition.rb
|
require 'digest/md5'
class AlarmDefinition
attr_reader :alarm_id, :notification_type, :definition
NOTIFICATION_TYPE_EMERGENCY = 'emergency'
NOTIFICATION_TYPE_ORDINARY = 'ordinary'
NOTIFICATION_TYPES = [NOTIFICATION_TYPE_EMERGENCY, NOTIFICATION_TYPE_ORDINARY]
# @param [Hash] definition
def initialize(definition)
@alarm_id = extract_alarm_id(definition)
@notification_type = extract_notification_type(definition)
@definition = definition
end
# @param [AlarmDefinition] definition
def ==(definition)
return false unless definition
self.alarm_id === definition.alarm_id
end
def name
@definition[:alarm_name]
end
private
# @param [Hash] definition
def extract_alarm_id(definition)
alarm_id = definition.delete(:alarm_id)
return alarm_id if alarm_id
Digest::MD5.hexdigest(definition[:alarm_name])
end
# @param [Hash] definition
def extract_notification_type(definition)
notification_type = definition.delete(:notification_type)
if NOTIFICATION_TYPES.include?(notification_type)
notification_type
else
puts "#{notification_type} is unknown notification type, use #{NOTIFICATION_TYPE_ORDINARY}."
NOTIFICATION_TYPE_ORDINARY
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/definitions/alarm_definitions.rb
|
<reponame>QLife-Inc/ec2-auto-metric-alarms<filename>src/libs/definitions/alarm_definitions.rb
# @attr_reader [Array<String>] include_definitions
# @attr_reader [Array<AlarmDefinition>] definitions
class AlarmDefinitions
attr_reader :include_definitions, :definitions
# @param [Hash] definitions
def initialize(definitions)
@include_definitions = definitions[:include_definitions] || []
@ignore_alarm_ids = definitions[:ignore_alarm_ids] || []
@definitions = (definitions[:alarm_definitions] || []).map do |definition|
AlarmDefinition.new(definition)
end
end
# @param [AlarmDefinition] definition
# @return [AlarmDefinitions]
def add_definition(definition)
if exists?(definition)
return
end
@definitions += [definition]
end
def remove_ignore_alarms
@ignore_alarm_ids.each {|alarm_id| remove_by_alarm_id(alarm_id)}
end
# @return [Boolean]
def empty?
@definitions.empty?
end
private
# @param [String] alarm_id
# @return [AlarmDefinitions]
def remove_by_alarm_id(alarm_id)
@definitions = @definitions.reject do |definition|
definition.alarm_id === alarm_id
end
end
# @param [AlarmDefinition] definition
# @return [AlarmDefinition]
def exists?(definition)
@definitions.find { |existance| existance == definition }
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/auto_alarm_facade_spec.rb
|
require 'spec_helper'
describe AutoAlarmFacade do
def create_instance(id, name, alarm_definition_name, exists = true)
tags = [
OpenStruct.new(key: 'Name', value: name),
OpenStruct.new(key: Settings.definition_tag_key, value: alarm_definition_name)
]
instance = OpenStruct.new(id: id, tags: tags)
allow(instance).to receive(:exists?).and_return(exists)
instance
end
let(:exists) { true }
let(:instance) { create_instance('i-12345', 'dummy', 'dummy-alarm-definition', exists) }
let(:ec2) { instance_double('AWS::EC2::Resource', instances: [instance], instance: instance) }
let(:definition) do
AlarmDefinition.new(
alarm_id: 'alarm-id',
notification_type: 'emergency',
alarm_name: 'dummy-alarm'
)
end
let(:resolver) { instance_double('AlarmDefinitionRsolver', resolve: [definition]) }
let(:alarm) do
instance_double('Alarm', exists?: exists, name: definition.name, update: nil, create: nil)
end
let(:resource) { instance_double('AlarmResource', alarm: alarm) }
let(:target) { described_class.new(ec2, resolver, resource) }
describe 'set_alarms_to_instance' do
before { target.send(:set_alarms_to_instance, instance) }
context 'when alarm is already exists' do
it 'called update' do
expect(alarm).to have_received(:update).once
end
end
context 'when alarm is not exists' do
let(:exists) { false }
it 'called create' do
expect(alarm).to have_received(:create).once
end
end
end
describe 'set_alarm_to_instances_auto' do
before do
allow(target).to receive(:set_alarms_to_instance).and_return(true)
target.set_alarm_to_instances_auto
end
subject { target }
it do
is_expected.to have_received(:set_alarms_to_instance).once
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/definitions/instance_wrapper.rb
|
<reponame>QLife-Inc/ec2-auto-metric-alarms<filename>src/libs/definitions/instance_wrapper.rb
class InstanceWrapper
# @param [Aws::EC2::Instance] instance
def initialize(instance)
@instance = instance
end
# @return [String]
def name
@name ||= tag_value('Name', @instance.id)
end
# @return [String]
def alarm_definition
@alarm_definition ||= tag_value(Settings.definition_tag_key)
end
# @param [String] key
# @param [String] default_value
# @return [String]
def tag_value(key, default_value = nil)
tag = tags.find { |t| t.key == key }
if tag
tag.value
else
default_value
end
end
private
def respond_to_missing?(name, include_private)
return true if super
@instance.respond_to?(name, include_private)
end
def method_missing(name, *args)
if @instance.respond_to?(name)
@instance.send(name, *args)
else
super
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/function.rb
|
require_relative './libs/loader'
FACADE = AutoAlarmFacadeFactory.create(
Aws::EC2::Resource.new,
Aws::S3::Client.new,
Aws::CloudWatch::Client.new
)
def lambda_handler(event:, context:)
event_type = event['detail-type']
instance_id = event.dig('detail', 'EC2InstanceId')
case event_type
when 'EC2 Instance Launch Successful'
FACADE.set_alarms_to_instance_by_id(instance_id)
when 'EC2 Instance Terminate Successful'
FACADE.delete_alarms_by_instance_id(instance_id)
else
FACADE.set_alarm_to_instances_auto
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/loader.rb
|
<gh_stars>1-10
require 'forwardable'
require_relative 'settings'
require_relative 'logable'
require_relative 'definitions/instance_wrapper'
require_relative 'definitions/alarm_definition'
require_relative 'definitions/alarm_definitions'
require_relative 'definitions/alarm_definition_template'
require_relative 'definitions/alarm_definition_repository'
require_relative 'definitions/alarm_definition_resolver'
require_relative 'alarms/alarm'
require_relative 'alarms/alarm_resource'
require_relative 'auto_alarm_facade'
require_relative 'auto_alarm_facade_factory'
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/definitions/alarm_definition_repository.rb
|
require 'aws-sdk-s3'
class AlarmDefinitionRepository
# @param [Aws::S3::Client] client
def initialize(client)
@s3 = Aws::S3::Resource.new(client: client)
@bucket = @s3.bucket(Settings.definition_bucket_name)
@prefix = Settings.definition_object_prefix
end
# @param [String] alarm_definition_name
# @return [AlamrDefinitionTemplate]
def get_alarm_definition(alarm_definition_name)
key = @prefix + alarm_definition_name
object = @bucket.object(key)
unless object.exists?
message = "s3://#{@bucket.name}/#{key} is not found."
puts message
return AlarmDefinitionTemplate.new("{\"error\":\"#{message}\"}")
end
AlarmDefinitionTemplate.new(object)
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/settings_spec.rb
|
require 'spec_helper'
describe Settings do
describe 'definition_bucket_name' do
before { ENV['DEFINITION_BUCKET_NAME'] = 'test_bucket' }
subject { described_class.definition_bucket_name }
it { is_expected.to eq 'test_bucket' }
end
describe 'definition_object_prefix' do
let(:prefix) { 'hoge/' }
before do
described_class.instance_variable_set(:@definition_object_prefix, nil)
ENV['DEFINITION_OBJECT_PREFIX'] = prefix
end
subject { described_class.definition_object_prefix }
context '末尾スラッシュがある場合' do
let(:prefix) { 'hoge/' }
it { is_expected.to eq 'hoge/' }
end
context '末尾スラッシュがない場合' do
let(:prefix) { 'hoge' }
it { is_expected.to eq 'hoge/' }
end
end
describe 'definition_tag_key' do
before do
described_class.instance_variable_set(:@definition_tag_key, nil)
ENV['DEFINITION_TAG_KEY'] = 'hogehoge'
end
subject { described_class.definition_tag_key }
it { is_expected.to eq 'hogehoge' }
end
describe 'emergency_topic_arn' do
before do
described_class.instance_variable_set(:@emergency_topic_arn, nil)
ENV['EMERGENCY_TOPIC_ARN'] = 'emergency'
end
subject { described_class.emergency_topic_arn }
it { is_expected.to eq 'emergency' }
end
describe 'ordinary_topic_arn' do
before do
described_class.instance_variable_set(:@ordinary_topic_arn, nil)
ENV['ORDINARY_TOPIC_ARN'] = 'ordinary'
end
subject { described_class.ordinary_topic_arn }
it { is_expected.to eq 'ordinary' }
end
describe 'logger' do
let(:log_level) { 'debug' }
before do
described_class.instance_variable_set(:@log_level, nil)
described_class.instance_variable_set(:@logger, nil)
ENV['LOG_LEVEL'] = log_level
end
subject { described_class.logger.level }
it { is_expected.to eq Logger::Severity::DEBUG }
context 'when log_level is not specified' do
let(:log_level) { nil }
it { is_expected.to eq Logger::Severity::INFO }
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/logable.rb
|
<filename>src/libs/logable.rb<gh_stars>1-10
module Logable
def logger
@logger ||= Settings.logger
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/spec_helper.rb
|
<reponame>QLife-Inc/ec2-auto-metric-alarms
require 'simplecov'
require 'simplecov-console'
FORMATTERS = [
SimpleCov::Formatter::HTMLFormatter,
SimpleCov::Formatter::Console,
]
SimpleCov.start do
add_filter '/vendor/'
add_filter '/src/vendor/'
add_filter '/spec/'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new(FORMATTERS)
end
require_relative '../src/libs/loader'
RSpec.configure do |config|
config.before(:all) do
ENV['DEFINITION_BUCKET_NAME'] = 'test_bucket'
ENV['DEFINITION_OBJECT_PREFIX'] = 'definitions/'
ENV['DEFINITION_TAG_KEY'] = 'AlarmDefinitionName'
ENV['EMERGENCY_TOPIC_ARN'] = 'emergency-topic'
ENV['ORDINARY_TOPIC_ARN'] = 'ordinary-topic'
ENV['LOG_LEVEL'] = 'debug'
end
config.after(:all) do
ENV['DEFINITION_BUCKET_NAME'] = nil
ENV['DEFINITION_OBJECT_PREFIX'] = nil
ENV['DEFINITION_TAG_KEY'] = nil
ENV['EMERGENCY_TOPIC_ARN'] = nil
ENV['ORDINARY_TOPIC_ARN'] = nil
ENV['LOG_LEVEL'] = nil
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/auto_alarm_facade.rb
|
class AutoAlarmFacade
include Logable
EC2_FILTERS = [ { name: 'tag-key', values: [ Settings.definition_tag_key ] } ]
# @param [Aws::EC2::Resource] ec2
# @param [AlarmDefinitionResolver] resolver
# @param [AlarmResource] resource
def initialize(ec2, resolver, resource)
@ec2 = ec2
@resolver = resolver
@resource = resource
end
def set_alarm_to_instances_auto
@ec2.instances(filters: EC2_FILTERS).each do |instance|
set_alarms_to_instance(instance)
end
end
# @param [String] instance_id
def set_alarms_to_instance_by_id(instance_id)
instance = get_instance(instance_id)
set_alarms_to_instance(instance)
end
# @param [String] instance_id
def delete_alarms_by_instance_id(instance_id)
instance = get_instance(instance_id)
delete_alarms_of_instance(instance)
end
private
# @param [Aws::EC2::Instance] instance
def set_alarms_to_instance(instance)
logger.debug("#{instance.id} にアラームを設定します")
@resolver.resolve(instance).each do |definition|
alarm = @resource.alarm(definition)
if alarm.exists?
alarm.update
logger.info("アラーム '#{alarm.name}' を更新しました")
else
alarm.create
logger.info("アラーム '#{alarm.name}' を作成しました")
end
end
end
# @param [Aws::EC2::Instance] instance
def delete_alarms_of_instance(instance)
logger.debug("#{instance.id} のアラームを削除します")
@resolver.resolve(instance).each do |definition|
alarm = @resource.alarm(definition)
return unless alarm.exists?
alarm.delete
logger.info("アラーム '#{alarm.name}' を削除しました")
end
@resource.alarms.select do |alarm|
alarm.name.include?(instance.id) || alarm.name.include?(instance.name)
end.each(&:delete)
end
def get_instance(instance_id)
instance = @ec2.instance(instance_id)
unless instance.exists?
raise "EC2 instance is not found: #{instance_id}"
end
instance
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
spec/libs/definitions/alarm_definition_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
describe AlarmDefinition do
let(:alarm_id) { 'alarm_id' }
let(:notification_type) { AlarmDefinition::NOTIFICATION_TYPE_EMERGENCY }
let(:definition) do
{
alarm_id: alarm_id, notification_type: notification_type,
alarm_name: 'テストアラーム',
namespace: 'AWS/EC2',
dimensions: [{ name: "InstanceId", value: "instance-id" }],
}
end
let(:target) { described_class.new(definition) }
describe 'initialize' do
it 'has alarm_id' do
expect(target.alarm_id).to eq alarm_id
end
it 'has notification_type' do
expect(target.notification_type).to eq notification_type
end
it 'has definition without alarm_id and notification_type' do
expect(target.definition).to eq(
{
alarm_name: 'テストアラーム',
namespace: 'AWS/EC2',
dimensions: [{ name: "InstanceId", value: "instance-id" }]
}
)
expect(target.definition.key?(:alarm_id)).to be_falsey
expect(target.definition.key?(:notification_type)).to be_falsey
end
end
describe 'name' do
subject { target.name }
it { is_expected.to eq 'テストアラーム' }
end
describe '==' do
let(:another) { described_class.new(alarm_id: alarm_id, alarm_name: 'ほげ') }
subject { target == another }
context 'when argument is nil' do
let(:another) { nil }
it { is_expected.to be_falsey }
end
context 'when alarm_id is same' do
it { is_expected.to be_truthy }
end
end
describe 'alarm_id_from_hash' do
subject { target.alarm_id }
context 'when alarm_id is missing' do
let(:alarm_id) { nil }
it { is_expected.to eq Digest::MD5.hexdigest(definition[:alarm_name]) }
end
end
describe 'notification_type_from_hash' do
subject { target.notification_type }
context 'when notification_id is unknown literal' do
let(:notification_type) { :hogehoge }
it { is_expected.to eq AlarmDefinition::NOTIFICATION_TYPE_ORDINARY }
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/settings.rb
|
class Settings
class << self
# @return [String]
def definition_bucket_name
@definition_bucket_name ||= ENV['DEFINITION_BUCKET_NAME']
end
# @return [String]
def definition_object_prefix
@definition_object_prefix ||= \
normalize_prefix(ENV['DEFINITION_OBJECT_PREFIX'])
end
# @return [String]
def definition_tag_key
@definition_tag_key ||= ENV['DEFINITION_TAG_KEY']
end
# @return [String]
def emergency_topic_arn
@emergency_topic_arn ||= ENV['EMERGENCY_TOPIC_ARN']
end
# @return [String]
def ordinary_topic_arn
@ordinary_topic_arn ||= ENV['ORDINARY_TOPIC_ARN']
end
# @return [Logger]
def logger
@logger ||= Logger.new(STDOUT, level: log_level)
end
# # @return [Pathname]
# def template_cache_path
# @cache_path ||= Pathname.new(ENV['LAMBDA_TASK_ROOT']) + 'cache'
# end
private
# @return [String]
def normalize_prefix(prefix)
return prefix unless prefix
(prefix.end_with?('/') ? prefix.chop : prefix) + '/'
end
# @return [Integer]
def log_level
@log_level ||= Logger::Severity.const_get(ENV['LOG_LEVEL']&.upcase || 'INFO')
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/auto_alarm_facade_factory.rb
|
require 'aws-sdk-ec2'
require 'aws-sdk-s3'
require 'aws-sdk-cloudwatch'
class AutoAlarmFacadeFactory
# @param [Aws::EC2::Resource] ec2
# @param [Aws::S3::Client] s3
# @param [Aws::CloudWatch::Client] cloudwatch
def self.create(ec2, s3, cloudwatch)
return new(ec2, s3, cloudwatch).create
end
# @param [Aws::EC2::Resource] ec2
# @param [Aws::S3::Client] s3
# @param [Aws::CloudWatch::Client] cloudwatch
def initialize(ec2, s3, cloudwatch)
@ec2 = ec2
@s3 = s3
@cloudwatch = cloudwatch
end
def create
AutoAlarmFacade.new(@ec2, resolver, resource)
end
private
def resource
AlarmResource.new(@cloudwatch)
end
def resolver
AlarmDefinitionResolver.new(repository)
end
def repository
AlarmDefinitionRepository.new(@s3)
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/definitions/alarm_definition_template.rb
|
require 'erb'
class AlarmDefinitionTemplate
attr_reader :body, :content_type
# @params [Aws::S3::Object, String] data
def initialize(data)
if data.is_a?(String)
@body = data
@content_type = 'text/json'
else
@body = data.get.body.read.to_s
@content_type = data.content_type&.downcase
end
end
# @param [InstanceWrapper] instance
# @return [String]
def render(instance)
ERB.new(body).result(binding)
end
def json?
!yaml?
end
def yaml?
content_type.include?('yaml')
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/definitions/alarm_definition_resolver.rb
|
require 'json'
require 'yaml'
class AlarmDefinitionResolver
# @params [AlarmDefinitionRepository] repository
def initialize(repository)
@repository = repository
end
# @param [Aws::EC2::Instance] instance
# @return [AlarmDefinitions]
def resolve(instance)
wrapped_instance = InstanceWrapper.new(instance)
resolve_definition(wrapped_instance.alarm_definition, wrapped_instance)
end
private
# @param [AlarmDefinitions] definitions
# @param [Array<AlarmDefinition>]
def resolve_definition(alarm_definition_name, instance)
definition_hash = get_alarm_definitions(alarm_definition_name, instance)
alarm_definitions = AlarmDefinitions.new(definition_hash)
alarm_definitions = resolve_include_definitions(alarm_definitions, instance)
alarm_definitions.remove_ignore_alarms
alarm_definitions.definitions
end
# @param [AlarmDefinitions] definitions
# @param [InstanceWrapper] instance
# @return [AlarmDefinitions]
def resolve_include_definitions(definitions, instance)
include_definitions = definitions.include_definitions.map do |definition_name|
resolve_definition(definition_name, instance) # recursive
end
include_definitions.flatten.each do |definition|
definitions.add_definition(definition)
end
definitions
end
# @param [String] alarm_definition_name
# @param [InstanceWrapper] instance
# @return [Hash]
def get_alarm_definitions(alarm_definition_name, instance)
template = @repository.get_alarm_definition(alarm_definition_name)
definition = template.render(instance)
if template.yaml?
YAML.load(definition, symbolize_names: true)
else
JSON.parse(definition, symbolize_names: true)
end
end
end
|
QLife-Inc/ec2-auto-metric-alarms
|
src/libs/alarms/alarm.rb
|
<reponame>QLife-Inc/ec2-auto-metric-alarms
class Alarm
extend Forwardable
include Logable
def_delegators :alarm, :exists?, :delete, :alarm_arn
def_delegators :@definition, :name
# @param [AlarmDefinition] definition
# @param [Aws::CloudWatch::Resource] cloudwatch
def initialize(definition, cloudwatch)
@definition = definition
@cloudwatch = cloudwatch
end
def create
if @definition.notification_type === AlarmDefinition::NOTIFICATION_TYPE_EMERGENCY
topics = [ Settings.emergency_topic_arn ]
else
topics = [ Settings.ordinary_topic_arn ]
end
actions = { ok_actions: topics, alarm_actions: topics }
request = actions.merge(@definition.definition)
response = @cloudwatch.client.put_metric_alarm(request)
logger.info("アラームを設定しました: name: #{name}, alarm: #{response.to_json}")
end
alias update create
private
# @return [Aws::CloudWatch::Alarm]
def alarm
@alarm ||= @cloudwatch.alarm(name)
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/railtie.rb
|
# encoding: utf-8
require 'rails'
module Pbl
class Railtie < ::Rails::Railtie
config.pbl_service_client = ActiveSupport::OrderedOptions.new
initializer "pbl_service_client.configure" do |app|
Pbl.config do |config|
config.base_url = app.config.pbl_service_client[:base_url]
config.version = app.config.pbl_service_client[:version]
end
end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/base/response.rb
|
<reponame>gxbsst/pbl_service_client
require 'pbl/base/response/extra_response'
require 'pbl/base/response/resource'
module Pbl
module Base
class Response
def self.build(listener, response, verb, options = {})
fail Pbl::Exceptions::InternalServerErrorException, '500 error', caller if response.response_code == 500
new(listener, response, verb, options).build
end
attr_reader :response, :listener, :resource, :options
def initialize(listener, response, verb = :find, options = {})
@response = response
@listener = listener
@resource = Resource.new(listener, response, verb)
@options = options
end
def build
resource.build_resource
end
end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/base/response/resource.rb
|
module Pbl
module Base
class Resource
attr_accessor :listener, :response, :body
def initialize(listener, response, verb)
@listener = listener
@response = response
@body = JSON.parse(response.body, symbolize_names: true) rescue nil
if verb == :create || verb == :update
self.extend CreatingResource
elsif verb == :find
self.extend FindingResource
elsif verb == :where
self.extend WhereResource
elsif verb == :destroy
self.extend DestroyResource
elsif verb == :custom
self.extend CustomResource
else
self.class.include NormalResource
end
end
def build_resource
result = build_model_resource.extend ExtraResponse
wrap_response(result)
end
def wrap_response(result)
result.body = response.body
result.code = response.response_code
result.headers = response.headers
result
end
# def build_model_resource
# nil
# end
end
module NormalResource
def build_model_resource
nil
end
end
module CreatingResource
def build_model_resource
if response.success?
listener.new(body)
else
listener.new.assign_errors(body)
end
end
end
module FindingResource
def build_model_resource
response.success? ? listener.new(body) : nil
end
end
module WhereResource
def build_model_resource
if response.success?
if !body[:data].blank?
{
:data => body[:data].map{ |record| listener.new(record) },
:meta => body[:meta]
}
else
{
:data => [],
:meta => []
}
end
else
nil
end
end
end
module DestroyResource
def build_model_resource
if response.success?
listener.new(body)
else
nil
end
end
end
module CustomResource
def build_model_resource
if response.success?
if !body[:data].blank?
{
:data => body[:data],
:meta => body[:meta]
}
else
{
:data => [],
:meta => []
}
end
else
nil
end
end
end
end
end
|
gxbsst/pbl_service_client
|
spec/spec_helper.rb
|
require 'bundler/setup'
Bundler.setup
require 'devise'
require 'devise_cas_authenticatable'
require 'pbl_service_client'
require 'webmock/rspec'
I18n.config.enforce_available_locales = false
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/config.rb
|
<reponame>gxbsst/pbl_service_client
require 'pbl/config/configure'
module Pbl
module Config
end
end
|
gxbsst/pbl_service_client
|
spec/models/projects/product_spec.rb
|
def create_product(product_object, options = {})
default_params.merge(options)
product_object.create(params)
end
describe Pbl::Models::Projects::Product do
shared_examples 'collect product' do
it { expect(product.form).to eq('form') }
it { expect(product.description).to eq('description') }
it { expect(product.is_final).to eq(false) }
it { expect(product.project_id).to eq('project_id') }
end
subject(:product_object) { described_class }
let(:default_params) {
{
product: {
form: 'form',
description: 'description',
is_final: false,
project_id: 'project_id'
}
}
}
describe '.create' do
context 'successful' do
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/pbl/products').to_return(
body: product_object.new(default_params[:product]).to_json,
status: 201
)
end
subject!(:product) { create_product(product_object, params) }
it { expect(product.code).to eq(201) }
it_behaves_like 'collect product'
end
context 'failed' do
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/pbl/products').to_return(
body: return_body,
status: 422,
headers: {'Header' => 'header'}
)
end
subject!(:product) { create_product(product_object, params) }
it { expect(product.code).to eq(422) }
it { expect(product.body).to eq(return_body) }
it { expect(product.headers).to eq({'Header' => 'header'}) }
end
end
describe '.update' do
context 'successful' do
let(:update_params) { {name: 'update_name'} }
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/products/1').to_return(
body: nil,
status: 200
)
end
subject(:update_product) { product_object.update('1', update_params) }
it { expect(update_product.body).to eq('') }
end
context 'failed' do
let(:update_params) { {name: 'update_name'} }
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/products/1').to_return(
body: return_body,
status: 422
)
end
subject(:update_product) { product_object.update('1', update_params) }
it { expect(update_product.code).to eq(422) }
it { expect(update_product.body).to eq(return_body) }
end
end
describe '.destroy' do
before(:each) do
stub_request(:delete, 'http://0.0.0.0:3001/pbl/products/1').to_return(
body: nil,
status: 200
)
end
subject(:result) { product_object.destroy(1) }
it { expect(result.code).to eq(200) }
it { expect(result.body).to eq('') }
end
describe '.find!' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/products/1').to_return(
body: product_object.new(default_params[:product]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/pbl/products/2').to_return(
body: nil,
status: 404
)
end
context 'product exist' do
subject(:product) { product_object.find!(1) }
it 'find' do
expect(product.success?).to be_truthy
expect(product.code).to eq(200)
expect(product.form).to eq('form')
expect(product.description).to eq('description')
expect(product.is_final).to eq(false)
expect(product.project_id).to eq('project_id')
end
end
context 'product do not exist' do
it { expect { product_object.find!(2) }.to raise_error(Pbl::Exceptions::NotFoundException) }
end
end
describe '.find' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/products/1').to_return(
body: product_object.new(default_params[:product]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/pbl/products/2').to_return(
body: '{}',
status: 404,
headers: {}
)
end
context 'product is exist' do
let(:product) { product_object.find(1) }
it 'find a product' do
expect(product).to be_truthy
expect(product.code).to eq(200)
expect(product.form).to eq('form')
expect(product.description).to eq('description')
expect(product.is_final).to eq(false)
expect(product.project_id).to eq('project_id')
end
end
context 'product is not exist' do
subject(:product) { product_object.find('2') }
it { expect(product.code).to eq(404) }
it { expect(product.headers).to be_a Hash }
it { expect(product.body).to eq('{}') }
it { expect(product.success?).to be_falsey }
end
end
describe '.where' do
before(:each) do
clazz_instances = []
clazz_instances << product_object.new(default_params[:product])
stub_request(:get, 'http://0.0.0.0:3001/pbl/products/').to_return(
body: {'data' => clazz_instances, 'meta' => {total_count: 1, total_pages: 1, per_page: 1, current_page: 1}}.to_json,
status: 200
)
end
let(:clazz_instances) { product_object.all }
it { expect(clazz_instances).to be_a Hash }
it { expect(clazz_instances.fetch(:data).first.form).to eq('form') }
it { expect(clazz_instances.fetch(:data).first.description).to eq('description') }
it { expect(clazz_instances.fetch(:meta)[:total_count]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:total_pages]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:per_page]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:current_page]).to eq(1) }
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/services.rb
|
<reponame>gxbsst/pbl_service_client<filename>lib/pbl/services.rb
require 'pbl/services/users/validate_password'
# alias namespace
module Pbl
module Services
# module Users
# ValidatePassword = ::Pbl::Services::Users::ValidatePassword
# end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/base.rb
|
<gh_stars>0
require 'pbl/base/client'
require 'pbl/base/response'
module Pbl
module Base
end
end
|
gxbsst/pbl_service_client
|
spec/services/users/validate_password_spec.rb
|
<gh_stars>0
describe Pbl::Services::Users::ValidatePassword do
let(:service) { described_class }
let(:user_object) { Pbl::Models::Users::User }
let(:default_params) {
{
user: {
username: 'username',
email: '<EMAIL>',
password: '<PASSWORD>',
first_name: 'first_name',
last_name: 'last_name',
age: 20,
gender: 1
}
}
}
context 'with valid password ' do
before(:each) do
stub_request(:post, "http://0.0.0.0:3001/users/#{default_params[:user][:email]}/actions/authenticate").to_return(
body: user_object.new(default_params[:user]).to_json,
status: 200
)
end
subject(:user) { service.call(default_params[:user][:email], 'secret') }
it { expect(user.email).to eq(default_params[:user][:email])}
it { expect(user.code).to eq(200) }
end
context 'with invalid password' do
before(:each) do
stub_request(:post, "http://0.0.0.0:3001/users/#{default_params[:user][:email]}/actions/authenticate").to_return(
body: JSON.generate({'error' => {}}),
status: 404
)
end
subject(:user) { service.call(default_params[:user][:email], 'error') }
it { expect(user.code).to eq(404)}
it { expect(user.headers).to eq(nil) }
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/models/users/user.rb
|
require 'pbl/models/concerns/base'
Devise::Models::CASAuthenticatable = Devise::Models::CasAuthenticatable
module Pbl
module Models
module Users
class User
extend Devise::Models
include Base
include ActiveModel::Validations::Callbacks
include ActiveModel::Serializers::JSON
# attribute :id, String
# attribute :username, String
# attribute :first_name, String
# attribute :last_name, String
# attribute :age, Integer
# attribute :gender, Integer
# attribute :email, String
# attribute :password_digest, String
# attribute :extra_attributes, Hash
devise :cas_authenticatable, :pbl_authenticatable
validates :first_name, :last_name, presence: true
def self.find_for_authentication(tainted_conditions)
find(tainted_conditions[:username])
end
def validate_password(email, password)
::Pbl::Services::Users::ValidatePassword.call(email, password)
end
# private
#
# def client
# @client ||= Pbl::Client.new(model_name: model_origin_name.pluralize)
# end
#
# def model_origin_name
# self.name.demodulize.to_s.underscore.downcase
# end
end
end
end
end
|
gxbsst/pbl_service_client
|
spec/models/curriculum/subject_spec.rb
|
<gh_stars>0
describe Pbl::Models::Curriculum::Subject do
subject(:subject_object) { described_class }
let(:default_params) {
{
subject: {
name: 'name',
position: 1,
phases: [
{
title: 'title1',
position: 1
}
]
}
}
}
describe '.find' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/curriculum/subjects/1').to_return(
body: subject_object.new(default_params[:subject]).to_json,
status: 200
)
end
context 'subject is exist' do
let(:subject) { subject_object.find(1) }
it 'find a subject' do
expect(subject).to be_truthy
expect(subject.code).to eq(200)
expect(subject.name).to eq('name')
expect(subject.position).to eq(1)
end
end
end
describe '.find with include' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/curriculum/subjects/1?include=phases').to_return(
body: subject_object.new(default_params[:subject]).to_json,
status: 200
)
end
context 'subject is exist' do
let(:subject) { subject_object.find(1, include: 'phases') }
it 'find a subject' do
expect(subject).to be_truthy
expect(subject.code).to eq(200)
expect(subject.name).to eq('name')
expect(subject.position).to eq(1)
# expect(subject.phases[0].position).to eq(1)
end
end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/models/projects/product_form.rb
|
<reponame>gxbsst/pbl_service_client
require 'pbl/models/concerns/base'
module Pbl
module Models
module Projects
class ProductForm
include Pbl::Models::Users::Base
include ActiveModel::Validations::Callbacks
include ActiveModel::Serializers::JSON
class << self
private
def client
@client ||= Pbl::Base::Client.new(model_name: model_origin_name.pluralize)
end
def model_origin_name
self.name.demodulize.to_s.underscore.downcase
end
end
end
end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl.rb
|
require 'active_model'
require 'virtus'
require 'typhoeus'
require 'json'
require 'pbl/railtie' if defined? ::Rails::Railtie
require 'pbl/config'
require 'pbl/base'
require 'pbl/exceptions'
require 'pbl/models'
require 'pbl/services'
module Pbl
#=================================
# Configure
#=================================
def self.configure
@@config ||= Config::Configure.new(base_url: 'http://0.0.0.0:3001')
end
def self.config
yield self.configure
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/base/client.rb
|
<filename>lib/pbl/base/client.rb
module Pbl
module Base
class Client
attr_accessor :model_name, :name_space
def initialize(params = {})
@model_name = params[:model_name]
@name_space = params.fetch(:name_space, nil)
end
def get(id, query_string = nil)
if query_string
resource = resource_with_query(id, query_string)
else
resource = resource(id)
end
::Typhoeus.get(resource, headers: headers)
end
def query(query_string)
::Typhoeus.get(resource(query_string, true), headers: headers)
end
# def look_for(id, query_string)
# ::Typhoeus.get(full_url(id, query_string), headers: headers)
# end
def post(body)
rest_client.post(base_url, body: body, headers: headers)
end
def patch(id, body)
rest_client.patch(resource(id), body: body, headers: headers)
end
def delete(id)
rest_client.delete(resource(id), headers: headers)
end
def post_action(id, action, body)
url = "#{base_url}/#{id}/actions/#{action}"
rest_client.post(url, body: body, headers: headers)
end
def custom(path, options = {})
params = options.fetch(:params, nil)
method = options.fetch(:method, :get)
body = options.fetch(:body, nil)
url = "#{base_url}/#{path}"
url << "?#{params}" if params.present?
if body
::Typhoeus.send(method.to_s, url, body: body, headers: headers)
else
::Typhoeus.send(method.to_s, url, headers: headers)
end
end
private
def rest_client
::Typhoeus::Request
end
def base_url
if name_space.present?
::Pbl.configure.base_url + "/#{name_space}" + "/" + model_name
else
::Pbl.configure.base_url + "/" + model_name
end
end
def headers
{
# 'content-type' => 'application/x-www-form-urlencoded',
'Accept' => "application/vnd.ibridgebrige.com; version=1"
}
end
def version
::Pbl.configure.version || 1
end
def resource(params, with_q = false)
if with_q
"#{base_url}/?#{params}"
else
"#{base_url}/#{params}"
end
end
def resource_with_query(params, query_string)
"#{base_url}/#{params}?#{query_string}"
end
# def full_url(id, params)
# "#{base_url}/#{id}?#{params}"
# end
end
end
end
|
gxbsst/pbl_service_client
|
spec/models/projects/project_spec.rb
|
def create_project(project_object, options = {})
default_params.merge(options)
project_object.create(params)
end
describe Pbl::Models::Projects::Project do
shared_examples 'collect project' do
it { expect(project.name).to eq('name') }
it { expect(project.description).to eq('description') }
it { expect(project.driven_issue).to eq('driven_issue') }
it { expect(project.standard_analysis).to eq('standard_analysis') }
it { expect(project.rule_head).to eq('rule_head') }
it { expect(project.rule_template).to eq('rule_template') }
end
subject(:project_object) { described_class }
let(:default_params) {
{
project: {
name: 'name',
description: 'description',
driven_issue: 'driven_issue',
standard_analysis: 'standard_analysis',
rule_head: 'rule_head',
rule_template: 'rule_template'
}
}
}
describe '.create' do
context 'successful' do
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/pbl/projects').to_return(
body: project_object.new(default_params[:project]).to_json,
status: 201
)
end
subject!(:project) { create_project(project_object, params)}
it { expect(project.code).to eq(201) }
it_behaves_like 'collect project'
end
context 'failed' do
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/pbl/projects').to_return(
body: return_body,
status: 422,
headers: {'Header' => 'header'}
)
end
subject!(:project) { create_project(project_object, params)}
it { expect(project.code).to eq(422)}
it { expect(project.body).to eq(return_body)}
it { expect(project.headers).to eq({'Header' => 'header'})}
end
end
describe '.update' do
context 'successful' do
let(:update_params) { {name: 'update_name' }}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/projects/1').to_return(
body: nil,
status: 200
)
end
subject(:update_project) { project_object.update('1', update_params)}
# it { expect(update_project.first_name).to eq('update_first_name') }
# it { expect(update_project.last_name).to eq('update_last_name') }
# it { expect(update_project.age).to eq(21) }
# it { expect(update_project.gender).to eq(0) }
# it { expect(update_project.code).to eq(200) }
it { expect(update_project.body).to eq('')}
end
context 'failed' do
let(:update_params) { {name: 'update_name' }}
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/projects/1').to_return(
body: return_body,
status: 422
)
end
subject(:update_project) { project_object.update('1', update_params)}
# it { expect(update_project.first_name).to eq('update_first_name') }
# it { expect(update_project.last_name).to eq('update_last_name') }
# it { expect(update_project.age).to eq(21) }
# it { expect(update_project.gender).to eq(0) }
it { expect(update_project.code).to eq(422) }
it { expect(update_project.body).to eq(return_body)}
end
end
describe '.release' do
let(:update_params) { {name: 'update_name' }}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/projects/1/actions/release?a=1').to_return(
body: project_object.new(default_params[:project]).to_json,
status: 200
)
end
subject(:release) { project_object.release(1, a: 1)}
it { expect(release.code).to eq(200) }
end
describe '.destroy' do
before(:each) do
stub_request(:delete, 'http://0.0.0.0:3001/pbl/projects/1').to_return(
body: nil,
status: 200
)
end
subject(:result) { project_object.destroy(1)}
it { expect(result.code).to eq(200)}
it { expect(result.body).to eq('')}
end
describe '.find!' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/1').to_return(
body: project_object.new(default_params[:project]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/2').to_return(
body: nil,
status: 404
)
end
context 'project exist' do
subject(:project) { project_object.find!(1)}
it 'find' do
expect(project.success?).to be_truthy
expect(project.code).to eq(200)
expect(project.name).to eq('name')
expect(project.description).to eq('description')
expect(project.driven_issue).to eq('driven_issue')
expect(project.standard_analysis).to eq('standard_analysis')
end
end
context 'project do not exist' do
it { expect{project_object.find!(2)}.to raise_error(Pbl::Exceptions::NotFoundException)}
end
end
describe '.find' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/1').to_return(
body: project_object.new(default_params[:project]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/2').to_return(
body: '{}',
status: 404,
headers: {}
)
end
context 'project is exist' do
let(:project) { project_object.find(1) }
it 'find a project' do
expect(project).to be_truthy
expect(project.code).to eq(200)
expect(project.name).to eq('name')
expect(project.description).to eq('description')
expect(project.driven_issue).to eq('driven_issue')
expect(project.standard_analysis).to eq('standard_analysis')
end
end
context 'project is not exist' do
subject(:project) { project_object.find('2')}
it { expect(project.code).to eq(404) }
it { expect(project.headers).to be_a Hash}
it { expect(project.body).to eq('{}') }
it { expect(project.success?).to be_falsey }
end
end
describe '.where' do
before(:each) do
clazz_instances = []
clazz_instances << project_object.new(default_params[:project])
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/').to_return(
body: {'data' => clazz_instances, 'meta' => {total_count: 1, total_pages: 1, per_page: 1, current_page: 1}}.to_json,
status: 200
)
end
let(:clazz_instances) { project_object.all }
it { expect(clazz_instances).to be_a Hash}
it { expect(clazz_instances[:data].first.name).to eq('name') }
it { expect(clazz_instances[:data].first.description).to eq('description') }
it { expect(clazz_instances[:meta][:total_count]).to eq(1) }
it { expect(clazz_instances[:meta][:total_pages]).to eq(1) }
it { expect(clazz_instances[:meta][:per_page]).to eq(1) }
it { expect(clazz_instances[:meta][:current_page]).to eq(1) }
context 'when a empty array' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/').to_return(
body: {'data' => [], 'meta' => {total_count: 1, total_pages: 1, per_page: 1, current_page: 1}}.to_json,
status: 200
)
end
let(:clazz_instances) { project_object.all }
it { expect(clazz_instances.fetch(:data)).to eq([]) }
end
context 'with include items' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/projects/').to_return(
body: {'data' => [{standard_items: {a: 1, b: 2}}], 'meta' => {total_count: 1, total_pages: 1, per_page: 1, current_page: 1}}.to_json,
status: 200
)
end
let(:clazz_instances) { project_object.all }
it { expect(clazz_instances.fetch(:data)[0][:standard_items]).to eq({a: 1, b: 2}) }
end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/models/projects/project.rb
|
require 'pbl/models/concerns/base'
module Pbl
module Models
module Projects
class Project
include Pbl::Models::Users::Base
include ActiveModel::Validations::Callbacks
include ActiveModel::Serializers::JSON
# attribute :id, String
# attribute :name, String
# attribute :description, String
# attribute :driven_issue, String
# attribute :standard_analysis, String
# attribute :duration, Integer
# attribute :public, Boolean
# attribute :limitation, String
# attribute :location_id, Integer
# attribute :grade_id, Integer
# attribute :rule_head, String
# attribute :rule_template, String
class << self
def release(id, params = {})
response = client.custom("#{id}/actions/release", params: query_string(params), method: :patch)
response_class.build(self, response, :update)
end
private
def client
@client ||= Pbl::Base::Client.new(model_name: model_origin_name.pluralize, name_space: 'pbl')
end
def model_origin_name
self.name.demodulize.to_s.underscore.downcase
end
end
end
end
end
end
|
gxbsst/pbl_service_client
|
spec/pbl/base/response_spec.rb
|
describe Pbl::Base::Response do
before(:each) do
stub_request(:any, "http://0.0.0.0:3001/users/222").to_return(:status => [500, "Internal Server Error"])
end
it 'raise a InternalServerErrorException' do
expect{Pbl::Models::Users::User.find('222')}.to raise_error(Pbl::Exceptions::InternalServerErrorException)
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/exceptions.rb
|
<gh_stars>0
require 'pbl/exceptions/not_found_exception'
require 'pbl/exceptions/internal_server_error_exception'
module Exceptions
end
|
gxbsst/pbl_service_client
|
lib/pbl/config/configure.rb
|
<gh_stars>0
module Pbl
module Config
class Configure
attr_accessor :base_url, :version
def initialize(params = {})
@base_url ||= params[:base_url]
@version ||= params[:version]
end
end
end
end
|
gxbsst/pbl_service_client
|
lib/pbl_service_client/version.rb
|
module PblServiceClient
VERSION = "0.0.25"
end
|
gxbsst/pbl_service_client
|
lib/devise/models/pbl_authenticatable.rb
|
<gh_stars>0
module Devise
module Models
module PblAuthenticatable
# extend ActiveSupport::Concern
module ClassMethods
def serialize_from_session(key, salt)
resource = Pbl::Models::Users::User.find(key)
resource if resource && salt == resource.authenticatable_salt
end
def serialize_into_session(resource)
[resource.username, resource.authenticatable_salt]
end
end
def authenticatable_salt
password_digest[0,29] if password_digest
end
end
end
end
Devise.add_module :pbl_authenticatable, :controller => :sessions
|
gxbsst/pbl_service_client
|
lib/pbl/models.rb
|
<filename>lib/pbl/models.rb
require 'pbl/models/users/user'
require 'pbl/models/projects/project'
require 'pbl/models/projects/product'
require 'pbl/models/projects/standard_decomposition'
require 'pbl/models/curriculum/standard_item'
require 'pbl/models/curriculum/standard'
require 'pbl/models/curriculum/phase'
require 'pbl/models/curriculum/subject'
require "pbl/models/skills/technique"
require "pbl/models/skills/sub_category"
require "pbl/models/skills/category"
require 'pbl/models/gauge'
require 'pbl/models/projects/rule'
require 'pbl/models/projects/technique'
require 'pbl/models/projects/standard_item'
require 'pbl/models/projects/knowledge'
require 'pbl/models/projects/task'
require 'pbl/models/projects/discipline'
require 'pbl/models/projects/product_form'
require 'pbl/models/assignment'
require 'pbl/models/role'
require 'pbl/models/resource'
require 'pbl/models/region'
require 'pbl/models/follow'
require 'pbl/models/groups/group'
require 'pbl/models/groups/member_ship'
require 'pbl/models/projects/discussion'
require 'pbl/models/assignments/work'
require 'pbl/models/assignments/score'
require 'pbl/models/comment'
require 'pbl/models/notification'
require 'pbl/models/invitation'
require 'pbl/models/school'
require 'pbl/models/grade'
require 'pbl/models/clazz'
require 'pbl/models/student'
require 'pbl/models/friend_ship'
require 'pbl/models/todos/todo'
require 'pbl/models/todos/todo_item'
require 'pbl/models/feeds/message'
require 'pbl/models/feeds/post'
require 'pbl/models/mail'
# alias namespace
module Pbl
module Models
# module Users
# User = ::Pbl::Models::Users::User
# end
end
end
|
gxbsst/pbl_service_client
|
spec/models/projects/standard_decomposition_spec.rb
|
<reponame>gxbsst/pbl_service_client
def create_standard_decomposition(standard_decomposition_object, options = {})
default_params.merge(options)
standard_decomposition_object.create(params)
end
describe Pbl::Models::Projects::StandardDecomposition do
shared_examples 'collect standard_decomposition' do
it { expect(standard_decomposition.role).to eq('role') }
it { expect(standard_decomposition.verb).to eq('verb') }
it { expect(standard_decomposition.technique).to eq('technique') }
it { expect(standard_decomposition.noun).to eq('noun') }
it { expect(standard_decomposition.product_name).to eq('product_name') }
it { expect(standard_decomposition.product_id).to eq('product_id') }
end
subject(:standard_decomposition_object) { described_class }
let(:default_params) {
{
standard_decomposition: {
role: 'role',
verb: 'verb',
technique: 'technique',
noun: 'noun',
product_name: 'product_name',
product_id: 'product_id'
}
}
}
describe '.create' do
context 'successful' do
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/pbl/standard_decompositions').to_return(
body: standard_decomposition_object.new(default_params[:standard_decomposition]).to_json,
status: 201
)
end
subject!(:standard_decomposition) { create_standard_decomposition(standard_decomposition_object, params) }
it { expect(standard_decomposition.code).to eq(201) }
it_behaves_like 'collect standard_decomposition'
end
context 'failed' do
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/pbl/standard_decompositions').to_return(
body: return_body,
status: 422,
headers: {'Header' => 'header'}
)
end
subject!(:standard_decomposition) { create_standard_decomposition(standard_decomposition_object, params) }
it { expect(standard_decomposition.code).to eq(422) }
it { expect(standard_decomposition.body).to eq(return_body) }
it { expect(standard_decomposition.headers).to eq({'Header' => 'header'}) }
end
end
describe '.update' do
context 'successful' do
let(:update_params) { {name: 'update_name'} }
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/standard_decompositions/1').to_return(
body: nil,
status: 200
)
end
subject(:update_standard_decomposition) { standard_decomposition_object.update('1', update_params) }
# it { expect(update_standard_decomposition.first_name).to eq('update_first_name') }
# it { expect(update_standard_decomposition.last_name).to eq('update_last_name') }
# it { expect(update_standard_decomposition.age).to eq(21) }
# it { expect(update_standard_decomposition.gender).to eq(0) }
# it { expect(update_standard_decomposition.code).to eq(200) }
it { expect(update_standard_decomposition.body).to eq('') }
end
context 'failed' do
let(:update_params) { {name: 'update_name'} }
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/pbl/standard_decompositions/1').to_return(
body: return_body,
status: 422
)
end
subject(:update_standard_decomposition) { standard_decomposition_object.update('1', update_params) }
it { expect(update_standard_decomposition.code).to eq(422) }
it { expect(update_standard_decomposition.body).to eq(return_body) }
end
end
describe '.destroy' do
before(:each) do
stub_request(:delete, 'http://0.0.0.0:3001/pbl/standard_decompositions/1').to_return(
body: nil,
status: 200
)
end
subject(:result) { standard_decomposition_object.destroy(1) }
it { expect(result.code).to eq(200) }
it { expect(result.body).to eq('') }
end
describe '.find!' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/standard_decompositions/1').to_return(
body: standard_decomposition_object.new(default_params[:standard_decomposition]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/pbl/standard_decompositions/2').to_return(
body: nil,
status: 404
)
end
context 'standard_decomposition exist' do
subject(:standard_decomposition) { standard_decomposition_object.find!(1) }
it 'find' do
expect(standard_decomposition.success?).to be_truthy
expect(standard_decomposition.code).to eq(200)
expect(standard_decomposition.role).to eq('role')
expect(standard_decomposition.verb).to eq('verb')
expect(standard_decomposition.technique).to eq('technique')
expect(standard_decomposition.noun).to eq('noun')
expect(standard_decomposition.product_name).to eq('product_name')
expect(standard_decomposition.product_id).to eq('product_id')
end
end
context 'standard_decomposition do not exist' do
it { expect { standard_decomposition_object.find!(2) }.to raise_error(Pbl::Exceptions::NotFoundException) }
end
end
describe '.find' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/pbl/standard_decompositions/1').to_return(
body: standard_decomposition_object.new(default_params[:standard_decomposition]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/pbl/standard_decompositions/2').to_return(
body: '{}',
status: 404,
headers: {}
)
end
context 'standard_decomposition is exist' do
let(:standard_decomposition) { standard_decomposition_object.find(1) }
it 'find a standard_decomposition' do
expect(standard_decomposition).to be_truthy
expect(standard_decomposition.code).to eq(200)
expect(standard_decomposition.role).to eq('role')
expect(standard_decomposition.verb).to eq('verb')
expect(standard_decomposition.technique).to eq('technique')
expect(standard_decomposition.noun).to eq('noun')
expect(standard_decomposition.product_name).to eq('product_name')
expect(standard_decomposition.product_id).to eq('product_id')
end
end
context 'standard_decomposition is not exist' do
subject(:standard_decomposition) { standard_decomposition_object.find('2') }
it { expect(standard_decomposition.code).to eq(404) }
it { expect(standard_decomposition.headers).to be_a Hash }
it { expect(standard_decomposition.body).to eq('{}') }
it { expect(standard_decomposition.success?).to be_falsey }
end
end
describe '.where' do
before(:each) do
clazz_instances = []
clazz_instances << standard_decomposition_object.new(default_params[:standard_decomposition])
stub_request(:get, 'http://0.0.0.0:3001/pbl/standard_decompositions/').to_return(
body: {'data' => clazz_instances, 'meta' => {total_count: 1, total_pages: 1, per_page: 1, current_page: 1}}.to_json,
status: 200
)
end
let(:clazz_instances) { standard_decomposition_object.all }
it { expect(clazz_instances).to be_a Hash }
it { expect(clazz_instances.fetch(:data).first.role).to eq('role') }
it { expect(clazz_instances.fetch(:data).first.verb).to eq('verb') }
it { expect(clazz_instances.fetch(:meta)[:total_count]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:total_pages]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:per_page]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:current_page]).to eq(1) }
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/exceptions/internal_server_error_exception.rb
|
module Pbl
module Exceptions
class InternalServerErrorException < StandardError
end
end
end
|
gxbsst/pbl_service_client
|
spec/models/user_spec.rb
|
def create_user(user_object, options = {})
default_params.merge(options)
user_object.create(params)
end
describe Pbl::Models::Users::User do
shared_examples 'collect user' do
it { expect(user.first_name).to eq('first_name') }
it { expect(user.last_name).to eq('last_name') }
it { expect(user.age).to eq(20) }
it { expect(user.gender).to eq(1) }
end
subject(:user_object) { described_class }
let(:default_params) {
{
user: {
username: 'username',
email: '<EMAIL>',
password: '<PASSWORD>',
first_name: 'first_name',
last_name: 'last_name',
age: 20,
gender: 1
}
}
}
describe '#valid' do
it 'be valid with a first_name, last_name, age, gender' do
user = user_object.new(first_name: 'first_name', last_name: 'last_name', age: 20, gender: 1)
expect(user).to be_valid
end
it 'invalid without first_name' do
user = user_object.new(last_name: 'last_name')
expect(user).to_not be_valid
end
it 'invalid without last_name' do
user = user_object.new(first_name: 'first_name')
expect(user).to_not be_valid
end
end
describe 'attributes' do
let(:user) { user_object.new(first_name: 'first_name', last_name: 'last_name', age: 20, gender: 1, something: 'something', ok: 'ok') }
# it { expect(user.something).to eq('something') }
it_behaves_like 'collect user'
end
describe '.create' do
context 'successful' do
let(:params) { {first_name: 'first_name', last_name: 'last_name', age: 20, gender: 1 }}
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/users').to_return(
body: user_object.new(default_params[:user]).to_json,
status: 201
)
end
subject!(:user) { create_user(user_object, params)}
it { expect(user.code).to eq(201) }
it_behaves_like 'collect user'
end
context 'failed' do
let(:return_body) {
body = {error: {firstname: ['first name error']}}
JSON.generate(body)
}
let(:params) { {first_name: 'first_name', last_name: 'last_name', age: 20, gender: 1 }}
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/users').to_return(
body: return_body,
status: 422,
headers: {'Header' => 'header'}
)
end
subject!(:user) { create_user(user_object, params)}
it { expect(user.code).to eq(422)}
it { expect(user.body).to eq(return_body)}
it { expect(user.headers).to eq({'Header' => 'header'})}
end
end
describe '.update' do
context 'successful' do
let(:update_params) { {first_name: 'update_first_name', last_name: 'update_last_name', age: 21, gender: 0 }}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/users/1').to_return(
body: nil,
status: 200
)
end
subject(:update_user) { user_object.update('1', update_params)}
# it { expect(update_user.first_name).to eq('update_first_name') }
# it { expect(update_user.last_name).to eq('update_last_name') }
# it { expect(update_user.age).to eq(21) }
# it { expect(update_user.gender).to eq(0) }
# it { expect(update_user.code).to eq(200) }
it { expect(update_user.body).to eq('')}
end
context 'failed' do
let(:update_params) { {first_name: 'update_first_name', last_name: 'update_last_name', age: 21, gender: 0 }}
let(:return_body) {
body = {error: {firstname: ['first name error']}}
JSON.generate(body)
}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/users/1').to_return(
body: return_body,
status: 422
)
end
subject(:update_user) { user_object.update('1', update_params)}
# it { expect(update_user.first_name).to eq('update_first_name') }
# it { expect(update_user.last_name).to eq('update_last_name') }
# it { expect(update_user.age).to eq(21) }
# it { expect(update_user.gender).to eq(0) }
it { expect(update_user.code).to eq(422) }
it { expect(update_user.body).to eq(return_body)}
end
end
describe '.destroy' do
before(:each) do
stub_request(:delete, 'http://0.0.0.0:3001/users/1').to_return(
body: nil,
status: 200
)
end
subject(:result) { user_object.destroy(1)}
it { expect(result.code).to eq(200)}
it { expect(result.body).to eq('')}
end
describe '.find!' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/users/1').to_return(
body: user_object.new(default_params[:user]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/users/2').to_return(
body: nil,
status: 404
)
end
context 'user exist' do
subject(:user) { user_object.find!(1)}
it 'find' do
expect(user.success?).to be_truthy
expect(user.code).to eq(200)
expect(user.first_name).to eq('first_name')
expect(user.last_name).to eq('last_name')
expect(user.age).to eq(20)
expect(user.gender).to eq(1)
end
end
context 'user do not exist' do
it { expect{user_object.find!(2)}.to raise_error(Pbl::Exceptions::NotFoundException)}
end
end
describe '.find' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/users/1').to_return(
body: user_object.new(default_params[:user]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/users/2').to_return(
body: '{}',
status: 404,
headers: {}
)
end
context 'user is exist' do
let(:user) { user_object.find(1) }
it { expect(user.success?).to be_truthy }
it { expect(user.code).to eq(200)}
it { expect(user.first_name).to eq('first_name') }
it { expect(user.last_name).to eq('last_name') }
it { expect(user.age).to eq(20) }
it { expect(user.gender).to eq(1) }
end
context 'user is not exist' do
subject(:user) { user_object.find('2')}
it { expect(user.code).to eq(404) }
it { expect(user.headers).to be_a Hash}
it { expect(user.body).to eq('{}') }
it { expect(user.success?).to be_falsey }
end
end
describe '.where' do
before(:each) do
users = []
users << user_object.new(default_params[:user])
stub_request(:get, 'http://0.0.0.0:3001/users/?email=<EMAIL>').to_return(
# body: user_object.new(default_params[:user]).to_json,
body: {'data' => users, 'meta' => {}}.to_json,
status: 200
)
end
let(:users) { user_object.where({email:'<EMAIL>'})}
it { expect(users).to be_a Hash}
it { expect(users.fetch(:data).first.first_name).to eq('first_name') }
it { expect(users.fetch(:data).first.last_name).to eq('last_name') }
it { expect(users.fetch(:data).first.age).to eq(20) }
it { expect(users.fetch(:data).first.gender).to eq(1) }
end
end
|
gxbsst/pbl_service_client
|
lib/pbl/services/users/validate_password.rb
|
<gh_stars>0
module Pbl
module Services
module Users
class ValidatePassword
def self.call(email, password)
object = new(email, password)
object.call
end
attr_accessor :email, :password
def initialize(email, password)
@email ||= email
@password ||= password
end
def call
response = client.post_action(email, 'authenticate', {password: password})
Pbl::Base::Response.build(Pbl::Models::Users::User, response, :find)
end
private
def client
@client ||= Pbl::Base::Client.new(model_name: 'users')
end
end
end
end
end
|
gxbsst/pbl_service_client
|
spec/models/follow_spec.rb
|
<reponame>gxbsst/pbl_service_client
def create_object(clazz, options = {})
default_params.merge(options)
clazz.create(params)
end
describe Pbl::Models::Follow do
shared_examples 'collect clazz_instance' do
it { expect(clazz_instance.technique_id).to eq('technique_id') }
end
subject(:clazz) { described_class }
let(:default_params) {
{
object: {
weight: 'weight',
level_1: 'level_1',
level_2: 'level_2',
level_3: 'level_3',
level_4: 'level_4',
level_5: 'level_5',
technique_id: 'technique_id',
}
}
}
describe '.create' do
context 'successful' do
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/follows').to_return(
body: clazz.new(default_params[:object]).to_json,
status: 201
)
end
subject!(:clazz_instance) { create_object(clazz, params)}
it { expect(clazz_instance.code).to eq(201) }
it_behaves_like 'collect clazz_instance'
end
context 'failed' do
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
let(:params) { {} }
before(:each) do
stub_request(:post, 'http://0.0.0.0:3001/follows').to_return(
body: return_body,
status: 422,
headers: {'Header' => 'header'}
)
end
subject!(:clazz_instance) { create_object(clazz, params)}
it { expect(clazz_instance.code).to eq(422)}
it { expect(clazz_instance.body).to eq(return_body)}
it { expect(clazz_instance.headers).to eq({'Header' => 'header'})}
end
end
describe '.update' do
context 'successful' do
let(:update_params) { {level_1: 'level' }}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/follows/1').to_return(
body: nil,
status: 200
)
end
subject(:clazz_instance) { clazz.update('1', update_params)}
it { expect(clazz_instance.body).to eq('')}
end
context 'failed' do
let(:update_params) { {level_1: 'update level' }}
let(:return_body) {
body = {error: {name: ['name error']}}
JSON.generate(body)
}
before(:each) do
stub_request(:patch, 'http://0.0.0.0:3001/follows/1').to_return(
body: return_body,
status: 422
)
end
subject(:clazz_instance) { clazz.update('1', update_params)}
it { expect(clazz_instance.code).to eq(422) }
it { expect(clazz_instance.body).to eq(return_body)}
end
end
describe '.destroy' do
before(:each) do
stub_request(:delete, 'http://0.0.0.0:3001/follows/1').to_return(
body: nil,
status: 200
)
end
subject(:clazz_instance) { clazz.destroy(1)}
it { expect(clazz_instance.code).to eq(200)}
it { expect(clazz_instance.body).to eq('')}
end
describe '.find!' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/follows/1').to_return(
body: clazz.new(default_params[:object]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/follows/2').to_return(
body: nil,
status: 404
)
end
context 'project exist' do
subject(:clazz_instance) { clazz.find!(1)}
it 'find' do
expect(clazz_instance.success?).to be_truthy
expect(clazz_instance.code).to eq(200)
expect(clazz_instance.level_1).to eq('level_1')
expect(clazz_instance.level_2).to eq('level_2')
expect(clazz_instance.level_3).to eq('level_3')
expect(clazz_instance.level_4).to eq('level_4')
expect(clazz_instance.level_5).to eq('level_5')
expect(clazz_instance.technique_id).to eq('technique_id')
end
end
context 'project do not exist' do
it { expect{clazz.find!(2)}.to raise_error(Pbl::Exceptions::NotFoundException)}
end
end
describe '.find' do
before(:each) do
stub_request(:get, 'http://0.0.0.0:3001/follows/1').to_return(
body: clazz.new(default_params[:object]).to_json,
status: 200
)
stub_request(:get, 'http://0.0.0.0:3001/follows/2').to_return(
body: '{}',
status: 404,
headers: {}
)
end
context 'project is exist' do
let(:clazz_instance) { clazz.find(1) }
it 'find a project' do
expect(clazz_instance).to be_truthy
expect(clazz_instance.code).to eq(200)
end
end
context 'project is not exist' do
subject(:clazz_instance) { clazz.find('2')}
it { expect(clazz_instance.code).to eq(404) }
it { expect(clazz_instance.headers).to be_a Hash}
it { expect(clazz_instance.body).to eq('{}') }
it { expect(clazz_instance.success?).to be_falsey }
end
end
describe '.where' do
before(:each) do
clazz_instances = []
clazz_instances << clazz.new(default_params[:object])
stub_request(:get, 'http://0.0.0.0:3001/follows/').to_return(
body: {'data' => clazz_instances, 'meta' => {total_count: 1, total_pages: 1, per_page: 1, current_page: 1}}.to_json,
status: 200
)
end
let(:clazz_instances) { clazz.all }
it { expect(clazz_instances).to be_a Hash}
it { expect(clazz_instances.fetch(:data).first.level_1).to eq('level_1') }
it { expect(clazz_instances.fetch(:meta)[:total_count]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:total_pages]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:per_page]).to eq(1) }
it { expect(clazz_instances.fetch(:meta)[:current_page]).to eq(1) }
end
end
|
gxbsst/pbl_service_client
|
lib/pbl_service_client.rb
|
<reponame>gxbsst/pbl_service_client
require 'pbl_service_client/version'
require 'devise/models/pbl_authenticatable'
require 'pbl'
module PblServiceClient
end
|
gxbsst/pbl_service_client
|
lib/pbl/models/concerns/base.rb
|
# encoding: utf-8
# == 获取网关接口的通用类
module Pbl
module Models
module Users
module Base
extend ActiveSupport::Concern
included do
require "addressable/uri"
# include Virtus.model
include ActiveModel::Model
extend ActiveModel::Naming
extend ActiveModel::Translation
include ActiveModel::Conversion
include ActiveModel::Validations
# include DynamicAttrable
def initialize(attributes = {})
extend(Virtus.model)
super(attributes)
end
def method_missing(method, *args)
method = method.to_s.underscore
if method =~ /.*=$/
attribute method.chomp('='), args[0].class unless respond_to?(method)
send(method, args[0])
elsif respond_to?(method)
send(method)
else
nil
end
end
end
def save
end
def assign_errors(error_data)
errors.add(:base, error_data[:error]) #if error_data[:error].is_a? Hash
# error_data[:error].each do |attribute, attribute_errors|
# attribute_errors.each do |error|
# self.errors.add(attribute, error)
# end
# end
end
def persisted?
id.present?
end
module ClassMethods
#
# ==== Examples
#
# User.find(id)
#
def find(id, options = {})
q = options.present? ? query_string(options) : nil
response_class.build(self, client.get(id, q), :find)
end
#
# ==== Examples
#
# User.find(id)
# == with include
#
# User.find(id, include: 'friends')
def find!(id, options = {})
q = options.present? ? query_string(options) : nil
response = client.get(id, q)
raise ::Pbl::Exceptions::NotFoundException.new if !response.success?
response_class.build(self, response, :find)
end
#
# ==== Examples
#
# User.where(username: 'username', age: 20)
#
def where(parameters={})
response = client.query(query_string(parameters))
response_class.build(self, response, :where)
end
alias_method :all, :where
def create(attributes={})
response = client.post(envelope(attributes) )
response_class.build(self, response, :create)
end
#
# ==== Examples
#
# User.create(username: 'username', age: 20)
# *return*
#
def update(id, attributes={})
response = client.patch(id, envelope(attributes))
response_class.build(self, response, :update)
end
def destroy(id)
response_class.build(self, client.delete(id), :destroy)
end
#
# ==== Examples
#
# User.look_for(1, include: 'books')
# *return*
#
def look_for(id, parameters={})
response = client.look_for(id, query_string(parameters))
response_class.build(self, response, :find)
end
private
def client
@client ||= Pbl::Base::Client.new(model_name: model_origin_name.pluralize)
end
def response_class
Pbl::Base::Response
end
def envelope(attributes)
envelope = {}
envelope[model_origin_name] = attributes
envelope
end
def model_origin_name
self.name.demodulize.to_s.underscore.downcase
end
def query_string(parameters)
parameters.reject!{ |key, value| value.blank? }
Addressable::URI.new.tap do |uri|
uri.query_values = parameters
end.query
end
end # end ClassMethods
module DynamicAttrable
def initialize(attrs)
attrs.each_pair {|k, v| send("#{k}=", v)}
super(attrs)
end
def method_missing(method, *args, &block)
method = method.to_s.underscore
unless method =~ /.*=$/
super
else
self.extend(Virtus.model)
attribute_name = method.to_s.chomp('=')
attribute :"#{attribute_name}", args[0].class
send method, args[0]
end
end
end
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.