repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
PikachuEXE/memcached_cloud_gem
|
spec/memcached_cloud_spec.rb
|
require 'spec_helper'
describe "Memcachier" do
let(:memcached_cloud_file) { File.join(File.dirname(__FILE__), '..', 'lib', 'memcached_cloud.rb') }
[ "MEMCACHE_SERVERS", "MEMCACHE_USERNAME", "MEMCACHE_PASSWORD" ].each do |var|
context var do
let(:memcached_cloud_var) { var.gsub "MEMCACHE", "MEMCACHEDCLOUD" }
before :each do
ENV[var] = nil
ENV[memcached_cloud_var] = nil
end
context 'when memcached_cloud env bar is not set'
it "not set by default" do
load memcached_cloud_file
expect(ENV[var]).to be_nil
end
it "copied from memcached_cloud" do
ENV[memcached_cloud_var] = "set"
load memcached_cloud_file
expect(ENV[var]).to eq "set"
end
it "overwritten by memcached_cloud" do
ENV[var] = "old"
ENV[memcached_cloud_var] = "new"
load memcached_cloud_file
expect(ENV[var]).to eq "new"
end
it "not removed by memcached_cloud" do
ENV[var] = "old"
load memcached_cloud_file
expect(ENV[var]).to eq "old"
end
end
end
end
|
olleolleolle/async-http-cache
|
gems.rb
|
source "https://rubygems.org"
# Specify your gem's dependencies in async-http-cache.gemspec
gemspec
# gem "async-http", path: "../async-http"
# gem "protocol-http", path: "../protocol-http"
# gem "protocol-http1", path: "../protocol-http1"
group :maintenance, optional: true do
gem "bake-modernize"
gem "bake-bundler"
end
|
olleolleolle/async-http-cache
|
async-http-cache.gemspec
|
require_relative "lib/async/http/cache/version"
Gem::Specification.new do |spec|
spec.name = "async-http-cache"
spec.version = Async::HTTP::Cache::VERSION
spec.summary = "Standard-compliant cache for async-http."
spec.authors = ["<NAME>"]
spec.license = "MIT"
spec.homepage = "https://github.com/socketry/async-http-cache"
spec.files = Dir.glob('{lib}/**/*', File::FNM_DOTMATCH, base: __dir__)
spec.required_ruby_version = ">= 2.3.0"
spec.add_dependency "async-http", "~> 0.56"
spec.add_development_dependency "async-rspec", "~> 1.10"
spec.add_development_dependency "covered"
spec.add_development_dependency "rspec"
end
|
olleolleolle/async-http-cache
|
lib/async/http/cache/general.rb
|
# frozen_string_literal: true
# Copyright, 2020, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'protocol/http/middleware'
require_relative 'body'
require_relative 'response'
require_relative 'store'
module Async
module HTTP
module Cache
class General < ::Protocol::HTTP::Middleware
CACHE_CONTROL = 'cache-control'
CONTENT_TYPE = 'content-type'
AUTHORIZATION = 'authorization'
COOKIE = 'cookie'
def initialize(app, store: Store.default)
super(app)
@count = 0
@store = store
end
attr :count
attr :store
def close
@store.close
ensure
super
end
def key(request)
@store.normalize(request)
[request.authority, request.method, request.path]
end
def cacheable?(request)
# We don't support caching requests which have a body:
if request.body
return false
end
# We can't cache upgraded requests:
if request.protocol
return false
end
# We only support caching GET and HEAD requests:
unless request.method == 'GET' || request.method == 'HEAD'
return false
end
if request.headers[AUTHORIZATION]
return false
end
if request.headers[COOKIE]
return false
end
# Otherwise, we can cache it:
return true
end
def wrap(key, request, response)
if response.status != 200
return response
end
if request.head? and body = response.body
unless body.empty?
Console.logger.warn(self) {"HEAD request resulted in non-empty body!"}
return response
end
end
return Body.wrap(response) do |response, body|
Console.logger.debug(self) {"Updating cache for #{key}..."}
@store.insert(key, request, Response.new(response, body))
end
end
def call(request)
key = self.key(request)
cache_control = request.headers[CACHE_CONTROL]
unless cache_control&.no_cache?
if response = @store.lookup(key, request)
Console.logger.debug(self) {"Cache hit for #{key}..."}
@count += 1
# Return the cached response:
return response
end
end
unless cache_control&.no_store?
if cacheable?(request)
return wrap(key, request, super)
end
end
return super
end
end
end
end
end
|
olleolleolle/async-http-cache
|
lib/async/http/cache/body.rb
|
# frozen_string_literal: true
#
# Copyright, 2020, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'protocol/http/body/rewindable'
require 'protocol/http/body/completable'
require 'protocol/http/body/digestable'
module Async
module HTTP
module Cache
module Body
TRAILER = 'trailer'
ETAG = 'etag'
def self.wrap(response, &block)
if body = response.body
if body.empty?
# A body that is empty? at the outset, is immutable. This generally only applies to HEAD requests.
yield response, body
else
# Insert a rewindable body so that we can cache the response body:
rewindable = ::Protocol::HTTP::Body::Rewindable.wrap(response)
unless response.headers.include?(ETAG)
# Compute a digest and add it to the response headers:
::Protocol::HTTP::Body::Digestable.wrap(response) do |wrapper|
response.headers.add(ETAG, wrapper.etag)
end
# Ensure the etag is listed as a trailer:
response.headers.add(TRAILER, ETAG)
end
# Wrap the response with the callback:
::Protocol::HTTP::Body::Completable.wrap(response) do |error|
if error
Console.logger.error(self) {error}
else
yield response, rewindable.buffered
end
end
end
else
yield response, nil
end
return response
end
end
end
end
end
|
olleolleolle/async-http-cache
|
spec/async/http/cache/body_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
# Copyright, 2020, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'async/http/cache/body'
RSpec.describe Async::HTTP::Cache::Body do
include_context RSpec::Memory
let(:body) {Protocol::HTTP::Body::Buffered.new(["Hello", "World"])}
let(:response) {Protocol::HTTP::Response[200, [], body]}
describe ".wrap" do
it "can buffer and stream bodies" do
invoked = false
described_class.wrap(response) do |response, body|
invoked = true
# The cached/buffered body:
expect(body.read).to be == "Hello"
expect(body.read).to be == "World"
expect(body.read).to be nil
end
body = response.body
# The actual body:
expect(body.read).to be == "Hello"
expect(body.read).to be == "World"
expect(body.read).to be nil
body.close
expect(invoked).to be true
end
it "ignores failed responses" do
invoked = false
described_class.wrap(response) do
invoked = true
end
body = response.body
expect(body.read).to be == "Hello"
body.close(IOError.new("failed"))
expect(invoked).to be false
end
end
end
|
olleolleolle/async-http-cache
|
spec/async/http/cache/server_context.rb
|
# Copyright, 2019, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'async/http/server'
require 'async/http/server'
require 'async/http/client'
require 'async/reactor'
require 'async/io/ssl_socket'
require 'async/http/endpoint'
require 'protocol/http/accept_encoding'
RSpec.shared_context Async::HTTP::Server do
include_context Async::RSpec::Reactor
let(:protocol) {Async::HTTP::Protocol::HTTP2}
let(:endpoint) {Async::HTTP::Endpoint.parse('http://127.0.0.1:9294', reuse_port: true)}
let!(:client) {Async::HTTP::Client.new(endpoint, protocol: protocol)}
let!(:server_task) do
reactor.async do
server.run
end
end
after(:each) do
client.close
server_task.stop
end
let(:server) do
Async::HTTP::Server.for(endpoint, protocol) do |request|
Protocol::HTTP::Response[200, {}, []]
end
end
end
|
olleolleolle/async-http-cache
|
lib/async/http/cache/store/vary.rb
|
# frozen_string_literal: true
# Copyright, 2020, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
module Async
module HTTP
module Cache
module Store
VARY = 'vary'
ACCEPT_ENCODING = 'accept-encoding'
class Vary
def initialize(delegate, vary = {})
@delegate = delegate
@vary = vary
end
def close
@delegate.close
end
attr :delegate
def normalize(request)
if accept_encoding = request.headers[ACCEPT_ENCODING]
if accept_encoding.include?("gzip")
request.headers.set(ACCEPT_ENCODING, "gzip")
else
request.headers.delete(ACCEPT_ENCODING)
end
end
end
def key_for(headers, vary)
vary.map{|key| headers[key]}
end
def lookup(key, request)
if vary = @vary[key]
# We should provide user-supported normalization here:
key = key + key_for(request.headers, vary)
end
return @delegate.lookup(key, request)
end
def insert(key, request, response)
if vary = response.headers[VARY]&.sort
@vary[key] = vary
key = key + key_for(request.headers, vary)
end
@delegate.insert(key, request, response)
end
end
end
end
end
end
|
olleolleolle/async-http-cache
|
lib/async/http/cache/response.rb
|
<gh_stars>1-10
# frozen_string_literal: true
# Copyright, 2020, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'protocol/http/response'
require 'async/clock'
module Async
module HTTP
module Cache
class Response < ::Protocol::HTTP::Response
CACHE_CONTROL = 'cache-control'
SET_COOKIE = 'set-cookie'
ETAG = 'etag'
X_CACHE = 'x-cache'
def initialize(response, body)
@generated_at = Async::Clock.now
super(
response.version,
response.status,
response.headers.flatten,
body,
response.protocol
)
@max_age = @headers[CACHE_CONTROL]&.max_age
@etag = nil
@headers.set(X_CACHE, 'hit')
end
attr :generated_at
def etag
@etag ||= @headers[ETAG]
end
def cachable?
if cache_control = @headers[CACHE_CONTROL]
if cache_control.private? || !cache_control.public?
return false
end
else
# No cache control header...
return false
end
if set_cookie = @headers[SET_COOKIE]
Console.logger.warn(self) {"Cannot cache response with set-cookie header!"}
return false
end
return true
end
def age
Async::Clock.now - @generated_at
end
def expired?
if @max_age
self.age > @max_age
end
end
def dup
dup = super
dup.body = @body.dup
dup.headers = @headers.dup
return dup
end
end
end
end
end
|
olleolleolle/async-http-cache
|
spec/async/http/cache_spec.rb
|
RSpec.describe Async::HTTP::Cache do
it "has a version number" do
expect(Async::HTTP::Cache::VERSION).not_to be nil
end
end
|
olleolleolle/async-http-cache
|
lib/async/http/cache/store/memory.rb
|
# frozen_string_literal: true
# Copyright, 2020, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
module Async
module HTTP
module Cache
module Store
class Memory
def initialize(limit: 1024)
@index = {}
@limit = limit
@hit = 0
@miss = 0
@pruned = 0
@gardener = Async(transient: true, annotation: self.class) do |task|
while true
task.sleep(60)
pruned = self.prune
@pruned += pruned
Console.logger.debug(self) do |buffer|
if pruned > 0
buffer.puts "Pruned #{pruned} entries."
end
buffer.puts "Hits: #{@hit} Misses: #{@miss} Pruned: #{@pruned} Ratio: #{(100.0*@hit/@miss).round(2)}%"
body_usage = @index.sum{|key, value| value.body.length}
buffer.puts "Index size: #{@index.size} Memory usage: #{(body_usage / 1024.0**2).round(2)}MiB"
# @index.each do |key, value|
# buffer.puts "#{key.join('-')}: #{value.body.length}B"
# end
end
end
end
end
def close
@gardener.stop
end
attr :index
IF_NONE_MATCH = 'if-none-match'
NOT_MODIFIED = ::Protocol::HTTP::Response[304]
def lookup(key, request)
if response = @index[key]
if response.expired?
@index.delete(key)
@pruned += 1
return nil
end
if etags = request.headers[IF_NONE_MATCH]
if etags.include?(response.etag)
return NOT_MODIFIED
end
end
@hit += 1
return response.dup
else
@miss += 1
return nil
end
end
def insert(key, request, response)
if @index.size < @limit
length = response.body&.length
if length.nil? or length < 1024*64
@index[key] = response
end
end
end
# @return [Integer] the number of pruned entries.
def prune
initial_count = @index.size
@index.delete_if do |key, value|
value.expired?
end
return initial_count - @index.size
end
end
end
end
end
end
|
olleolleolle/async-http-cache
|
spec/async/http/cache/general_spec.rb
|
<reponame>olleolleolle/async-http-cache
# Copyright, 2017, by <NAME>. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require_relative 'server_context'
require 'async/http/cache/general'
RSpec.shared_examples_for Async::HTTP::Cache::General do
it "should cache GET requests" do
response = subject.get("/")
expect(response.read).to be == "Hello World"
10.times do
response = subject.get("/")
expect(response.read).to be == "Hello World"
end
expect(cache).to have_attributes(count: 10)
end
it "should cache HEAD requests" do
response = subject.head("/")
content_length = response.body.length
expect(content_length).to be == 11
expect(response.read).to be_nil
10.times do
response = subject.head("/")
expect(response.body.length).to be == content_length
expect(response.read).to be_nil
end
expect(cache).to have_attributes(count: 10)
end
it "should not cache POST requests" do
response = subject.post("/")
expect(response.read).to be == "Hello World"
response = subject.post("/")
expect(response.read).to be == "Hello World"
expect(cache).to have_attributes(count: 0)
end
context 'with varied response' do
let(:app) do
Protocol::HTTP::Middleware.for do |request|
response = if user_agent = request.headers['user-agent']
Protocol::HTTP::Response[200, [['cache-control', 'max-age=1, public'], ['vary', 'user-agent']], [user_agent]]
else
Protocol::HTTP::Response[200, [['cache-control', 'max-age=1, public'], ['vary', 'user-agent']], ['Hello', ' ', 'World']]
end
if request.head?
response.body = Protocol::HTTP::Body::Head.for(response.body)
end
response
end
end
let(:user_agents) {[
'test-a',
'test-b',
]}
it "should cache GET requests" do
2.times do
user_agents.each do |user_agent|
response = subject.get("/", {'user-agent' => user_agent})
expect(response.headers['vary']).to include('user-agent')
expect(response.read).to be == user_agent
end
end
expect(store.index.size).to be 2
end
end
context 'with if-none-match' do
it 'validate etag' do
# First, warm up the cache:
response = subject.get("/")
expect(response.headers).to_not include('etag')
expect(response.read).to be == "Hello World"
expect(response.headers).to include('etag')
etag = response.headers['etag']
response = subject.get("/", {'if-none-match' => etag})
expect(response).to be_not_modified
end
end
end
RSpec.describe Async::HTTP::Cache::General do
include_context Async::HTTP::Server
let(:app) do
Protocol::HTTP::Middleware.for do |request|
body = Async::HTTP::Body::Writable.new(11)
Async do |task|
body.write "Hello"
body.write " "
task.yield
body.write "World"
body.close
rescue Async::HTTP::Body::Writable::Closed
# Ignore... probably head request.
end
response = Protocol::HTTP::Response[200, [['cache-control', 'max-age=1, public']], body]
if request.head?
response.body = Protocol::HTTP::Body::Head.for(response.body)
end
response
end
end
let(:server) do
Async::HTTP::Server.new(app, endpoint, protocol: protocol)
end
let(:store) {cache.store.delegate}
context 'with client-side cache' do
subject(:cache) {described_class.new(client)}
let(:store) {subject.store.delegate}
include_examples Async::HTTP::Cache::General
end
context 'with server-side cache via HTTP/1.1' do
let(:protocol) {Async::HTTP::Protocol::HTTP11}
subject {client}
let(:cache) {described_class.new(app)}
let(:server) do
Async::HTTP::Server.new(cache, endpoint, protocol: protocol)
end
include_examples Async::HTTP::Cache::General
end
context 'with server-side cache via HTTP/2' do
let(:protocol) {Async::HTTP::Protocol::HTTP2}
subject {client}
let(:cache) {described_class.new(app)}
let(:server) do
Async::HTTP::Server.new(cache, endpoint, protocol: protocol)
end
include_examples Async::HTTP::Cache::General
end
end
|
tablexi/txi_rails_hologram
|
lib/txi_rails_hologram/engine.rb
|
<filename>lib/txi_rails_hologram/engine.rb
require "jquery-rails"
require "hologram"
require "txi_rails_hologram/template_variables_ext"
module TxiRailsHologram
# A mountable Rails engine that integrates Hologram with Rails.
class Engine < ::Rails::Engine
isolate_namespace TxiRailsHologram
config.generators do |g|
g.test_framework :rspec, fixture: false
g.assets false
g.helper false
end
initializer "txi_rails_hologram.assets.precompile" do |app|
app.config.assets.precompile += %w(jquery.js)
end
end
end
|
tablexi/txi_rails_hologram
|
spec/lib/txi_rails_hologram/template_variables_ext_spec.rb
|
<reponame>tablexi/txi_rails_hologram<gh_stars>1-10
require_relative "../../spec_helper"
require "txi_rails_hologram/rendering_context"
require "txi_rails_hologram/template_variables_ext"
describe "TemplateVariables Extension" do
let(:rendering_context) { spy }
subject { Hologram::TemplateVariables.new({}) }
before do
allow(TxiRailsHologram::RenderingContext).to receive(:instance)
.and_return(rendering_context)
end
it "delegates stylesheet_link_tag to the context" do
subject.stylesheet_link_tag("one")
expect(rendering_context).to have_received(:stylesheet_link_tag).with("one")
end
it "delegates stylesheet_link_tag to the context" do
subject.javascript_include_tag("two")
expect(rendering_context).to have_received(:javascript_include_tag).with("two")
end
it "delegates stylesheet_link_tag to the context" do
subject.asset_path("three")
expect(rendering_context).to have_received(:asset_path).with("three")
end
end
|
tablexi/txi_rails_hologram
|
lib/txi_rails_hologram/rendering_context.rb
|
require "haml"
module TxiRailsHologram
# Public: A context for rendering HAML that knows about helpers from Rails,
# gems and the current application.
class RenderingContext
# Internal: Creates a new context into which we can render a chunk of HAML.
#
# Returns a properly-configured instance of ActionView::Base.
def self.create
# Create a new instance of ActionView::Base that has all of the helpers
# that our ApplicationController does. This allows us to use normal Rails
# helpers like `link_to`, most gem-provided helpers, and also custom
# application helpers like `svg_icon`.
view_context = ApplicationController.helpers
# Add named route support to our view context, so we can reference things
# like `root_path`.
class << view_context; include Rails.application.routes.url_helpers; end
# Create a new controller instance and give it a fake request; this vaguely
# mirrors what happens when Rails receives a request and routes it. This
# step allows us to use `simple_form_for`.
controller = ApplicationController.new
controller.request = ActionDispatch::TestRequest.new
view_context.request = controller.request
# Set up our view paths so that both `render` and gems that provide helpers
# that use `render` (e.g. kaminari) can work.
controller.append_view_path "app/views"
view_context.view_paths = controller.view_paths
view_context.controller = controller
# Add support for capturing HAML via the helpers module.
class << view_context; include Haml::Helpers; end
# This call is needed since we're outside the typical Rails setup. See:
# https://github.com/haml/haml/blob/88110b0607efca433c13bb1e339dcb1131edf010/lib/haml/helpers.rb#L56-L70
view_context.init_haml_helpers
ViewContextWrapper.new(view_context)
end
private_class_method :create
# Public: A Singleton instance of the context.
def self.instance
@instance ||= create
end
# Public: A decorator around an ActionView::Base object that provides some
# custom functionality around loading assets that are specific to this
# gem's host application. This allows us to account for variance in setup
# of CSS and JS files across projects.
class ViewContextWrapper < SimpleDelegator
# Public: The content that should be loaded in the <head> for the
# particular host application.
#
# Returns a String.
def application_specific_styleguide_head
render_assets(config["styleguide_head"], "lib/assets/_default_styleguide_head.html.haml")
end
# Public: The content that should be loaded in the foot (right before the
# closing </body> tag) of the particular host application.
#
# Returns a String.
def application_specific_styleguide_foot
render_assets(config["styleguide_foot"], "lib/assets/_default_styleguide_foot.html.haml")
end
private
# Internal: The configuration from the hologram_config.yml file of the
# host application.
#
# Returns a Hash.
def config
@config ||= YAML.load(File.read(Rails.root.join("hologram_config.yml")))
end
# Internal: Renders the HAML content at the app_file_path or fallback_path.
#
# app_file_path - A String path relative to the host application's
# Rails.root, e.g. `styleguide/assets/_head.html.haml`
# fallback_path - A String path relative to the gem's root, e.g.
# `lib/assets/_default_head.html.haml`
#
# Returns a String.
def render_assets(app_file_path, fallback_path)
if app_file_path
content = File.read(Rails.root.join(app_file_path))
else
gem_path = Bundler.rubygems.find_name("txi_rails_hologram").first.full_gem_path
content = File.read("#{gem_path}/#{fallback_path}")
end
engine = Haml::Engine.new(content)
engine.render(self)
end
end
end
end
|
tablexi/txi_rails_hologram
|
spec/lib/txi_rails_hologram/rendering_context_spec.rb
|
require_relative "../../spec_helper"
require "txi_rails_hologram/rendering_context"
describe TxiRailsHologram::RenderingContext do
subject { described_class.instance }
it "handles named routes" do
expect(subject.root_path).to eq("/")
end
it "handles helper methods defined in application" do
expect(subject.strong_text("Fierce")).to eq("<strong>Fierce</strong>")
end
it "handles stock Rails helper methods" do
expect(subject.link_to("Example", "http://example.com"))
.to include(%(a href="http://example.com))
end
it "handles rendering partials" do
expect(subject.render("shared/logo"))
.to include(%(img src="/images/logo.svg))
end
it "handles helpers from other gems" do
expect(subject.hcard(fn: "First Last")).to include(%(vcard))
end
end
|
tablexi/txi_rails_hologram
|
lib/guard/txi_rails_hologram/version.rb
|
module Guard
module TxiRailsHologramVersion
VERSION = "1.0.0"
end
end
|
tablexi/txi_rails_hologram
|
lib/tasks/txi_rails_hologram_tasks.rake
|
require "txi_rails_hologram/builder"
desc "Explaining what the task does"
namespace :txi_rails_hologram do
task build: :environment do
config = YAML.load_file(Rails.root.join("hologram_config.yml"))
TxiRailsHologram::Builder.new.build(config)
end
end
|
tablexi/txi_rails_hologram
|
lib/txi_rails_hologram/builder.rb
|
<reponame>tablexi/txi_rails_hologram<gh_stars>1-10
module TxiRailsHologram
# Public: A thin wrapper around `Hologram::DocBuilder` that allows us to
# specify our own set of renderers, templates, and documentation assets.
class Builder
# Internal: A set of default options to pass to `Hologram::DocuBuilder`.
# These can be overwritten in the Rails app's `hologram_config.yml` file.
attr_reader :defaults
# Public: Initialize this object.
def initialize
gem_path = Bundler.rubygems.find_name("txi_rails_hologram").first.full_gem_path
@defaults = {
"code_example_renderers" => "#{gem_path}/lib/renderers",
"code_example_templates" => "#{gem_path}/lib/templates",
"documentation_assets" => "#{gem_path}/lib/assets",
"name_scope" => " - ",
"custom_extensions" => ".coffee",
}.freeze
end
# Public: Build the hologram docs using the Rails app's configuration.
#
# config - A Hash containing config options for the `Hologram::DocBuilder`.
# NOTE: hologram expects String keys.
#
# Returns nothing.
def build(config)
config = defaults.merge(config)
config["config_yml"] = config
config["renderer"] = Hologram::Utils.get_markdown_renderer(config["custom_markdown"])
config["base_path"] = "."
builder = Hologram::DocBuilder.new(config)
if builder.is_valid?
builder.build
else
$stderr.puts builder.errors
end
end
end
end
|
tablexi/txi_rails_hologram
|
lib/txi_rails_hologram.rb
|
<gh_stars>1-10
require "txi_rails_hologram/engine"
# Public: A namespace for this engine's functionality.
module TxiRailsHologram
end
|
tablexi/txi_rails_hologram
|
spec/lib/txi_rails_hologram/builder_spec.rb
|
require_relative "../../spec_helper"
require "txi_rails_hologram/builder"
describe TxiRailsHologram::Builder do
subject { described_class.new }
describe "#build" do
context "with valid params" do
let(:destination) { Dir.mktmpdir }
before do
config = {
"source" => [Rails.root.join("app/assets/stylesheets")],
"destination" => destination,
}
subject.build(config)
end
it "creates a styleguide" do
expect(File.exist?(File.join(destination, "basics.html"))).to be_truthy
end
it "puts in the default head" do
expect(File.read(File.join(destination, "basics.html"))).to match(/application.*\.css/)
end
it "puts in a custom foot" do
expect(File.read(File.join(destination, "basics.html"))).to match(/custom/i)
end
end
end
end
|
tablexi/txi_rails_hologram
|
spec/dummy/app/helpers/application_helper.rb
|
# Public: A place to store small view-related functions.
module ApplicationHelper
# Public: Outputs the text in a `strong` tag.
#
# text - A String.
#
# Returns a String of HTML.
def strong_text(text)
content_tag(:strong, text)
end
end
|
tablexi/txi_rails_hologram
|
lib/renderers/coffee_renderer.rb
|
require "coffee-script"
Hologram::CodeExampleRenderer::Factory.define("coffee") do
example_template "coffee_example_template"
lexer { Rouge::Lexer.find(:coffee) }
rendered_example do |code|
CoffeeScript.compile(code)
end
end
|
tablexi/txi_rails_hologram
|
lib/txi_rails_hologram/version.rb
|
# A namespace for this gem's functionality.
module TxiRailsHologram
# Public: The version of this gem.
VERSION = "0.0.2"
end
|
tablexi/txi_rails_hologram
|
txi_rails_hologram.gemspec
|
<gh_stars>1-10
$LOAD_PATH.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "txi_rails_hologram/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "txi_rails_hologram"
s.version = TxiRailsHologram::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/tablexi/txi_rails_hologram"
s.summary = "Living style guides using Hologram and Rails"
s.description = "Allows Rails-aware rendering in Hologram documentation, allowing the use of helpers and other Rails-related Ruby shenanigans."
s.license = "MIT"
s.files = Dir["{app,config,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
s.test_files = Dir["spec/**/*"]
s.add_dependency "rails", "~> 4.2"
s.add_dependency "hologram", "~> 1.4"
s.add_dependency "haml"
s.add_dependency "coffee-script"
s.add_dependency "sass"
s.add_dependency "jquery-rails"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "microformats_helper"
end
|
tablexi/txi_rails_hologram
|
lib/txi_rails_hologram/template_variables_ext.rb
|
# The `Hologram::TemplateVariables` is used as the context object when
# rendering ERb in the `DocBuilder`'s `write_docs` method. We monkey-patch it
# to allow the usage of some general layout-related Rails helper methods in our
# ERb documentation assets.
Hologram::TemplateVariables.class_eval do
extend Forwardable
def_delegators(
"TxiRailsHologram::RenderingContext.instance",
# Rails-specific:
:stylesheet_link_tag,
:javascript_include_tag,
:asset_path,
# Our own custom functionality:
:application_specific_styleguide_head,
:application_specific_styleguide_foot,
)
end
|
tablexi/txi_rails_hologram
|
lib/renderers/haml_renderer.rb
|
<reponame>tablexi/txi_rails_hologram<filename>lib/renderers/haml_renderer.rb
require "txi_rails_hologram/rendering_context"
require "haml"
# We overwrite the default "haml" handler from hologram to use our Rails-aware
# version.
Hologram::CodeExampleRenderer::Factory.define "haml" do
example_template "markup_example_template"
table_template "markup_table_template"
lexer { Rouge::Lexer.find("haml") }
rendered_example do |code|
haml_engine = Haml::Engine.new(code.strip)
context = TxiRailsHologram::RenderingContext.instance
haml_engine.render(context, {})
end
end
|
tablexi/txi_rails_hologram
|
spec/dummy/config/initializers/helpers.rb
|
require "microformats_helper"
|
tablexi/txi_rails_hologram
|
lib/guard/txi_rails_hologram.rb
|
<reponame>tablexi/txi_rails_hologram<filename>lib/guard/txi_rails_hologram.rb
require "guard/txi_rails_hologram/version"
require "guard"
require "guard/plugin"
module Guard
class TxiRailsHologram < Plugin
include TxiRailsHologramVersion
# Called when just `enter` is pressed
# This method should be principally used for long action like running all specs/tests/...
#
# @raise [:task_has_failed] when run_all has failed
# @return [Object] the task result
#
def run_all
system("bundle exec rake txi_rails_hologram:build") or throw :task_has_failed
end
# Default behaviour on file(s) changes that the Guard plugin watches.
# @param [Array<String>] paths the changes files or paths
# @raise [:task_has_failed] when run_on_change has failed
# @return [Object] the task result
#
def run_on_changes(paths)
run_all
end
# Called on file(s) additions that the Guard plugin watches.
#
# @param [Array<String>] paths the changes files or paths
# @raise [:task_has_failed] when run_on_additions has failed
# @return [Object] the task result
#
def run_on_additions(paths)
run_all
end
# Called on file(s) modifications that the Guard plugin watches.
#
# @param [Array<String>] paths the changes files or paths
# @raise [:task_has_failed] when run_on_modifications has failed
# @return [Object] the task result
#
def run_on_modifications(paths)
run_all
end
# Called on file(s) removals that the Guard plugin watches.
#
# @param [Array<String>] paths the changes files or paths
# @raise [:task_has_failed] when run_on_removals has failed
# @return [Object] the task result
#
def run_on_removals(paths)
run_all
end
end
end
|
tablexi/txi_rails_hologram
|
spec/dummy/config/routes.rb
|
<gh_stars>1-10
Rails.application.routes.draw do
mount TxiRailsHologram::Engine => "/txi_rails_hologram"
root to: "examples#index"
end
|
PhilippMatthes/FlyoverKit
|
FlyoverKit.podspec
|
Pod::Spec.new do |s|
s.name = "FlyoverKit"
s.version = "1.3.0"
s.summary = "360° flyover on an MKMapView"
s.homepage = "https://github.com/SvenTiigi/FlyoverKit"
s.social_media_url = 'http://twitter.com/SvenTiigi'
s.license = 'MIT'
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/SvenTiigi/FlyoverKit.git", :tag => s.version.to_s }
s.ios.deployment_target = "9.0"
s.tvos.deployment_target = "10.0"
s.requires_arc = true
s.source_files = 'Sources/**/*'
s.frameworks = 'UIKit', 'MapKit'
end
|
mlavandero/git-autoremove
|
lib/git/autoremove/version.rb
|
module Git
module Autoremove
VERSION = "0.1.0"
end
end
|
mlavandero/git-autoremove
|
lib/git/autoremove.rb
|
require "git/autoremove/version"
module Git
module Autoremove
end
end
|
jfelchner/homebrew-shell
|
Formula/bats-assert.rb
|
class BatsAssert < Formula
desc "Common assertions for Bats"
homepage "https://github.com/ztombol/bats-assert"
url "https://github.com/ztombol/bats-assert/archive/v0.3.0.tar.gz"
sha256 "0d447e4efc488cf06ebed3dea5b55e1fb909e572fb3576434194a09485f8a7f3"
head "https://github.com/ztombol/bats-assert.git"
depends_on "bats-support"
def install
mkdir "bats-assert"
mv "load.bash", "bats-assert/"
mv "src", "bats-assert/"
mv "test", "bats-assert/"
lib.install "bats-assert"
end
def caveats
<<-EOS.undent
To load the bats-assert lib in your bats test:
load '#{HOMEBREW_PREFIX}/lib/bats-support/load.bash'
load '#{HOMEBREW_PREFIX}/lib/bats-assert/load.bash'
EOS
end
test do
ENV["TEST_DEPS_DIR"] = "#{HOMEBREW_PREFIX}/lib"
system "bats", "#{lib}/bats-assert/test"
end
end
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq.rb
|
require 'set'
require 'active_support/inflector'
require 'active_support/core_ext/hash'
require 'concurrent'
require 'attentive_sidekiq/api'
require 'attentive_sidekiq/middleware/server/attentionist'
require 'attentive_sidekiq/middleware/client/attentionist'
require 'attentive_sidekiq/updater_observer'
require 'attentive_sidekiq/manager'
require 'sidekiq/web' unless defined?(Sidekiq::Web)
require 'attentive_sidekiq/web'
module AttentiveSidekiq
DEFAULTS = {
timeout_interval: 60,
execution_interval: 600
}
REDIS_SUSPICIOUS_KEY = "attentive_observed_hash"
REDIS_DISAPPEARED_KEY = "attentive_disappeared_hash"
class << self
attr_writer :timeout_interval, :execution_interval, :logger
def timeout_interval
return @timeout_interval if @timeout_interval
@timeout_interval = options[:timeout_interval] || DEFAULTS[:timeout_interval]
end
def execution_interval
return @execution_interval if @execution_interval
@execution_interval = options[:execution_interval] || DEFAULTS[:execution_interval]
end
def logger
@logger ||= Sidekiq.logger
end
def options
Sidekiq.options[:attentive] || Sidekiq.options['attentive'] || {}
end
end
end
AttentiveSidekiq::Manager.instance.start! if Sidekiq.server?
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq/middleware/server/attentionist.rb
|
<reponame>autumncollection/attentive_sidekiq
module AttentiveSidekiq
module Middleware
module Server
class Attentionist
def call(worker_instance, item, queue)
Suspicious.add(item)
yield
ensure
Suspicious.remove(item['jid'])
end
end
end
end
end
|
autumncollection/attentive_sidekiq
|
test/manager_test.rb
|
<filename>test/manager_test.rb
require "test_helper"
class ManagerTest < Minitest::Test
describe "with real redis" do
before do
Sidekiq.redis = REDIS
Sidekiq.redis{ |c| c.flushdb }
common_hash = {'class' => 'UnexistantWorker', 'args' => [], 'created_at' => Time.now.to_i}
@item_in_progress = {'jid' => "REDA-257513", 'queue' => 'red_queue'}.merge!(common_hash)
@item_disappeared = {'jid' => "YE11OW5-247", 'queue' => 'yellow_queue'}.merge!(common_hash)
AttentiveSidekiq::Suspicious.add @item_in_progress
AttentiveSidekiq::Suspicious.add @item_disappeared
@active_job_ids = [@item_in_progress['jid']]
end
it "removes lone job from suspicious and adds to disappeared" do
AttentiveSidekiq::Active.stub(:job_ids, @active_job_ids) do
AttentiveSidekiq::Manager.instance.update_disappeared_jobs
assert_includes disappeared_now, @item_disappeared
refute_includes suspicious_now, @item_disappeared
end
end
it "leaves jobs which are being currently processed in suspicious" do
AttentiveSidekiq::Active.stub(:job_ids, @active_job_ids) do
AttentiveSidekiq::Manager.instance.update_disappeared_jobs
assert_includes suspicious_now, @item_in_progress
refute_includes disappeared_now, @item_in_progress
end
end
def suspicious_now
Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.map{|i| JSON.parse(i)}
end
def disappeared_now
from_redis = Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_DISAPPEARED_KEY)}
from_redis.map{|i| JSON.parse(i).except('noticed_at', 'status')}
end
end
end
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq/api.rb
|
module AttentiveSidekiq
class RedisBasedHash
class << self
def jobs
Sidekiq.redis{|conn| conn.hvals(hash_name)}.map{|i| JSON.parse(i)}
end
def job_ids
jobs.map{|i| i["jid"]}
end
def get_job jid
JSON.parse(Sidekiq.redis{|conn| conn.hget(hash_name, jid)})
end
def add item
Sidekiq.redis{ |conn| conn.hset(hash_name, item['jid'], item.to_json) }
end
def remove jid
Sidekiq.redis{|conn| conn.hdel(hash_name, jid)}
end
end
end
class Disappeared < RedisBasedHash
STATUS_DETECTED = 'detected'
STATUS_REQUEUED = 'requeued'
SIDEKIQ_PUSH_OPTIONS = %w[queue class args retry backtrace].freeze
class << self
alias_method :base_add, :add
def add item
extended_item = {'noticed_at' => Time.now.to_i, 'status' => STATUS_DETECTED}.merge(item)
super extended_item
end
def requeue jid
record = get_job(jid)
Sidekiq::Client.push(create_options(record))
base_add(record.merge('status' => STATUS_REQUEUED))
end
def hash_name
AttentiveSidekiq::REDIS_DISAPPEARED_KEY
end
private
def create_options(item)
SIDEKIQ_PUSH_OPTIONS.each_with_object({}) do |option, mem|
mem[option] = item[option] if item.include?(option)
end
end
end
end
class Suspicious < RedisBasedHash
class << self
def hash_name
AttentiveSidekiq::REDIS_SUSPICIOUS_KEY
end
end
end
class Active
class << self
def jobs
Sidekiq::Workers.new.to_a.map{|i| i[2]["payload"]}
end
def job_ids
Set.new(jobs.map{|i| i["jid"]})
end
end
end
end
|
autumncollection/attentive_sidekiq
|
test/server_middleware_test.rb
|
require "test_helper"
class ServerMiddlewareTest < Minitest::Test
describe "with real redis" do
before do
Sidekiq.redis = REDIS
Sidekiq.redis{ |c| c.flushdb }
@mutex = Mutex.new
@stopper = ConditionVariable.new
end
class HardWorker
include Sidekiq::Worker
def perform(seed, work_amount = 10)
raise "wrong amount of work" if work_amount <= 0
1.upto(work_amount) do |i|
1.upto(work_amount) do |j|
1.upto(work_amount) do |k|
i*j*k
end
end
end
end
end
class SidekiqEmulator
@@instance = SidekiqEmulator.new
def self.instance
@@instance
end
def process_jobs
processor.send(:process, work_unit)
end
private_class_method :new
private
def processor
::Sidekiq::Processor.new(manager)
end
def manager
options = { :concurrency => 1, :queues => ['default'] }
Sidekiq::Manager.new(options)
end
def work_unit
fetch = Sidekiq::BasicFetch.new(:queues => ['default'])
fetch.retrieve_work
end
end
class DefaultQueue
@@instance = DefaultQueue.new
def self.instance
@@instance
end
def size
queue.size rescue 0
end
def queue
::Sidekiq::Queue.new
end
private_class_method :new
end
it "does not mark job as suspicious while its queued" do
assert_equal 0, DefaultQueue.instance.size
HardWorker.perform_async(1)
assert_equal 1, DefaultQueue.instance.size
assert_equal 0, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
end
it "marks job as suspicious as soon as it is started" do
assert_equal 0, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
HardWorker.perform_async(2, 100_000)
Thread.new{
SidekiqEmulator.instance.process_jobs
}
sleep(1) # TODO: refactor this somehow
assert_equal 1, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
end
it "removes suspicious mark as soon as job is finished succesfully" do
assert_equal 0, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
HardWorker.perform_async(2, 1)
Thread.new{
@mutex.synchronize{
SidekiqEmulator.instance.process_jobs
@stopper.signal
}
}
@mutex.synchronize{ @stopper.wait(@mutex) }
assert_equal 0, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
end
it "removes suspicious mark as soon as job failed" do
assert_equal 0, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
HardWorker.perform_async(2, -1)
Thread.new{
@mutex.synchronize{
SidekiqEmulator.instance.process_jobs rescue nil
@stopper.signal
}
}
@mutex.synchronize{ @stopper.wait(@mutex) }
assert_equal 0, Sidekiq.redis{|conn| conn.hvals(AttentiveSidekiq::REDIS_SUSPICIOUS_KEY)}.size
end
end
end
|
autumncollection/attentive_sidekiq
|
test/web_test.rb
|
<reponame>autumncollection/attentive_sidekiq
require "test_helper"
require "rack/test"
class WebTest < Minitest::Test
include Rack::Test::Methods
def setup
Sidekiq.redis = REDIS
Sidekiq.redis{ |c| c.flushdb }
common_hash = {'class' => 'UnexistantWorker', 'args' => [], 'created_at' => Time.now.to_i}
@item_disappeared = {'jid' => "YE11OW5-247", 'queue' => 'yellow_queue'}.merge!(common_hash)
@item_in_progress = {'jid' => "REDA-257513", 'queue' => 'red_queue'}.merge!(common_hash)
AttentiveSidekiq::Suspicious.add(@item_in_progress)
AttentiveSidekiq::Disappeared.add(@item_disappeared)
end
def test_displays_jobs_in_disappeared_hash
get '/disappeared-jobs'
assert_equal 200, last_response.status
assert_match @item_disappeared['jid'], last_response.body
end
def test_does_not_display_jobs_not_in_disappeared_hash
get '/disappeared-jobs'
assert_equal 200, last_response.status
refute_match @item_in_progress['jid'], last_response.body
end
def test_delete_all_route_functions_fine
AttentiveSidekiq::Disappeared.stub(:remove, nil) do
post "/disappeared-jobs/delete-all"
follow_redirect!
assert_equal 200, last_response.status
end
end
def test_requeue_all_route_functions_fine
AttentiveSidekiq::Disappeared.stub(:requeue, nil) do
post "/disappeared-jobs/requeue-all"
follow_redirect!
assert_equal 200, last_response.status
end
end
def test_delete_route_functions_fine
AttentiveSidekiq::Disappeared.stub(:remove, nil) do
post "/disappeared-jobs/#{@item_disappeared['jid']}/delete"
follow_redirect!
assert_equal 200, last_response.status
end
end
def test_requeue_route_functions_fine
AttentiveSidekiq::Disappeared.stub(:requeue, nil) do
post "/disappeared-jobs/#{@item_disappeared['jid']}/requeue"
follow_redirect!
assert_equal 200, last_response.status
end
end
private
def app
Sidekiq::Web
end
end
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq/updater_observer.rb
|
<reponame>autumncollection/attentive_sidekiq
module AttentiveSidekiq
class UpdaterObserver
def update time, result, ex
if result
AttentiveSidekiq.logger.info("#{time} [AttentiveSidekiq] Finished updating with result #{result}")
elsif ex.is_a?(Concurrent::TimeoutError)
AttentiveSidekiq.logger.error("#{time} [AttentiveSidekiq] Execution timed out")
else
AttentiveSidekiq.logger.error("#{time } [AttentiveSidekiq] Execution failed with error #{ex}\n")
end
end
end
end
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq/web.rb
|
<reponame>autumncollection/attentive_sidekiq<gh_stars>10-100
module AttentiveSidekiq
module Web
VIEW_PATH = File.expand_path("../web/views", __FILE__)
def self.registered(app)
app.get("/disappeared-jobs") do
@disappeared_jobs = AttentiveSidekiq::Disappeared.jobs
erb File.read(File.join(VIEW_PATH, 'disappeared-list.erb'))
end
app.post("/disappeared-jobs/requeue-all") do
AttentiveSidekiq::Disappeared.jobs.each do |job|
if job['status'] == 'detected'
AttentiveSidekiq::Disappeared.requeue(job['jid'])
end
end
redirect "#{root_path}disappeared-jobs"
end
app.post("/disappeared-jobs/delete-all") do
AttentiveSidekiq::Disappeared.jobs.each do |job|
AttentiveSidekiq::Disappeared.remove(job['jid'])
end
redirect "#{root_path}disappeared-jobs"
end
app.post("/disappeared-jobs/:jid/delete") do
AttentiveSidekiq::Disappeared.remove(params['jid'])
redirect "#{root_path}disappeared-jobs"
end
app.post("/disappeared-jobs/:jid/requeue") do
AttentiveSidekiq::Disappeared.requeue(params['jid'])
redirect "#{root_path}disappeared-jobs"
end
end
end
end
Sidekiq::Web.register AttentiveSidekiq::Web
Sidekiq::Web.locales << File.expand_path(File.dirname(__FILE__) + "/web/locales")
Sidekiq::Web.tabs['disappeared_jobs'] = 'disappeared-jobs'
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq/manager.rb
|
<reponame>autumncollection/attentive_sidekiq<filename>lib/attentive_sidekiq/manager.rb
module AttentiveSidekiq
class Manager
@@instance = AttentiveSidekiq::Manager.new
def self.instance
@@instance
end
def start!
task = Concurrent::TimerTask.new(options) do
AttentiveSidekiq::Manager.instance.update_disappeared_jobs
end
task.add_observer(AttentiveSidekiq::UpdaterObserver.new)
task.execute
end
def update_disappeared_jobs
suspicious = AttentiveSidekiq::Suspicious.jobs
active_ids = AttentiveSidekiq::Active.job_ids
those_lost = suspicious.delete_if{|i| active_ids.include?(i["jid"])}
# Sidekiq might have been too fast finishing up a job that appeared in the suspicious list
# but didn't make it to the active list, so that's a false-positive.
# We need to get the new suspicious list again, and remove any lost jobs that are no longer there.
# Those jobs that appeared in the first suspicious list, but not the second one were simply finished
# quickly by Sidekiq before showing up as active by a worker.
suspicious = AttentiveSidekiq::Suspicious.jobs
those_lost.delete_if{|i| !suspicious.any?{|j| i['jid'] == j['jid']} }
those_lost.each do |job|
Disappeared.add(job)
Suspicious.remove(job['jid'])
end
end
private_class_method :new
private
def options
{
execution_interval: AttentiveSidekiq.execution_interval,
timeout_interval: AttentiveSidekiq.timeout_interval
}
end
end
end
|
autumncollection/attentive_sidekiq
|
attentive_sidekiq.gemspec
|
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'attentive_sidekiq/version'
Gem::Specification.new do |s|
s.name = 'attentive_sidekiq'
s.version = AttentiveSidekiq::VERSION
s.summary = "Make your sidekiq to be attentive to lost jobs"
s.description = "This gem allows you to watch the jobs which suddenly dissappeared from redis without being completed by redis worker"
s.authors = ["twonegatives"]
s.email = '<EMAIL>'
s.files = Dir['**/*'].keep_if{ |file| File.file?(file) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.homepage =
'http://rubygems.org/gems/attentive_sidekiq'
s.license = 'MIT'
s.add_development_dependency 'sidekiq', '~> 4.2'
s.add_development_dependency 'rake', '~> 11.3'
s.add_development_dependency 'minitest', '~> 5.0'
s.add_development_dependency 'minitest-stub_any_instance'
s.add_development_dependency 'redis-namespace', '~> 1.5'
s.add_development_dependency "rack-test", '~> 0.6'
s.add_development_dependency 'pry', '~> 0.10'
s.add_development_dependency "pry-byebug"
s.add_dependency "activesupport"
s.add_dependency 'concurrent-ruby', '~> 1.0'
end
|
autumncollection/attentive_sidekiq
|
test/api_test.rb
|
require_relative "test_helper"
class ApiTest < Minitest::Test
describe "with real redis" do
before do
Sidekiq.redis = REDIS
Sidekiq.redis { |c| c.flushdb }
simple_hash = {'class' => 'ApiTest::SimpleWorker', 'args' => [], 'created_at' => Time.now.to_i}
args_hash = {'args' => [1, "boo", "woo"], 'class' => 'ApiTest::WorkerWithArgs', 'created_at' => Time.now.to_i}
optional_options = { 'retry' => true, 'backtrace' => false }
@item_in_progress = {'jid' => "REDA-257513", 'queue' => 'red_queue'}.merge!(simple_hash)
@disappeared_wo_args = {'jid' => "YE11OW5-247", 'queue' => 'yellow_queue'}.merge!(simple_hash)
@disappeared_with_args = {'jid' => "B1UE-441", 'queue' => 'blue_queue'}.merge!(args_hash)
@disappeared_with_all_args_possible = { 'jid' => 'B1UE-441-ALL', 'queue' => 'blue_queue' }.merge(args_hash.merge(optional_options))
AttentiveSidekiq::Suspicious.add(@item_in_progress)
AttentiveSidekiq::Disappeared.add(@disappeared_wo_args)
AttentiveSidekiq::Disappeared.add(@disappeared_with_args)
AttentiveSidekiq::Disappeared.add(@disappeared_with_all_args_possible)
end
class BaseWorker
include Sidekiq::Worker
end
class SimpleWorker < BaseWorker
def perform
end
end
class WorkerWithArgs < BaseWorker
def perform a, b, c
end
end
describe 'requeue' do
it "adds jobs without args to sidekiq queue" do
item = @disappeared_wo_args
assert_equal 0, returned_queue(item).size
AttentiveSidekiq::Disappeared.requeue(item['jid'])
assert_equal 1, returned_queue(item).size
element = item_in_returned_queue(item)
assert_equal item['class'], element['class']
assert_equal item['args'], element['args']
end
it 'adds 2 jobs with args to sidekiq queue' do
item = @disappeared_with_args
item_all_args = @disappeared_with_all_args_possible
AttentiveSidekiq::Disappeared.requeue(item['jid'])
AttentiveSidekiq::Disappeared.requeue(item_all_args['jid'])
element = item_in_returned_queue(item)
element_with_all_args = item_in_returned_queue(item_all_args, 1)
assert_equal(item['class'], element['class'])
assert_equal(item['args'], element['args'])
(AttentiveSidekiq::Disappeared::SIDEKIQ_PUSH_OPTIONS - %w[backtrace]).each do |key|
assert_equal(item_all_args[key], element_with_all_args[key])
end
end
it "marks jobs as requeued" do
item = @disappeared_wo_args
assert_equal job_status(item), AttentiveSidekiq::Disappeared::STATUS_DETECTED
AttentiveSidekiq::Disappeared.requeue(item['jid'])
assert_equal job_status(item), AttentiveSidekiq::Disappeared::STATUS_REQUEUED
end
def returned_queue(item)
Sidekiq::Queue.new(item['queue'])
end
def item_in_returned_queue(item, position = 0)
returned_queue(item).to_a[position]
end
def job_status(item)
AttentiveSidekiq::Disappeared.get_job(item['jid'])['status']
end
end
end
end
|
autumncollection/attentive_sidekiq
|
test/test_helper.rb
|
ENV['RACK_ENV'] = ENV['RAILS_ENV'] = 'test'
require 'pry'
require 'sidekiq'
require 'sidekiq/api'
require 'sidekiq/cli'
require 'sidekiq/processor'
require 'sidekiq/manager'
require 'sidekiq/util'
require 'sidekiq/redis_connection'
require 'redis-namespace'
require 'attentive_sidekiq'
require 'minitest/autorun'
require 'minitest/pride'
require 'minitest/stub_any_instance'
REDIS_URL = ENV["REDIS_URL"] || "redis://localhost:6379/15"
REDIS_NAMESPACE = ENV["REDIS_NAMESPACE"] || 'testy'
REDIS = Sidekiq::RedisConnection.create(:url => REDIS_URL, :namespace => REDIS_NAMESPACE)
Sidekiq.configure_server do |config|
config.server_middleware do |chain|
chain.add AttentiveSidekiq::Middleware::Server::Attentionist
end
end
Sidekiq.logger = nil
|
autumncollection/attentive_sidekiq
|
lib/attentive_sidekiq/middleware/client/attentionist.rb
|
module AttentiveSidekiq
module Middleware
module Client
class Attentionist
def call(worker_class, item, queue, redis_pool = nil)
# TODO: we could backup job info here aswell
# this would lead us to the need of more complex records filtering
yield
end
end
end
end
end
|
makevoid/animeface-2009
|
animeface-ruby/eyecolor.rb
|
<reponame>makevoid/animeface-2009<filename>animeface-ruby/eyecolor.rb<gh_stars>100-1000
# coding: utf-8
# イラストの顔の目の色をクルクルするGIFアニメを作るコマンド
# AnimeFace-Ruby.tar.gzの最新版(2011/4/11 21時以降)が必要
#
# ruby eyecolor.rb homu.jpg homu.gif
require "rubygems"
require "rmagick"
require_relative "AnimeFace"
module AnimeFace
module EyeColor
def self.change(src, face, hsl, dest = nil)
dest ||= src.copy
change_eyecolor(dest, src, eye_info(face["eyes"]["left"]), hsl)
change_eyecolor(dest, src, eye_info(face["eyes"]["right"]), hsl)
dest
end
private
S = Magick::QuantumRange * 0.5
B = 0.6
A = 1.0
def self.change_eyecolor(dest, src, eye, hsl)
rect = {
:x1 => [eye[:center][:x] - eye[:r] * 1.5, 0].max.to_i,
:y1 => [eye[:center][:y] - eye[:r] * 1.5, 0].max.to_i,
:x2 => [eye[:center][:x] + eye[:r] * 1.5, src.columns].min.to_i,
:y2 => [eye[:center][:y] + eye[:r] * 1.5, src.rows].min.to_i
}
(rect[:x1] ... rect[:x2]).each do |x|
(rect[:y1] ... rect[:y2]).each do |y|
p = src.pixel_color(x, y)
# 目の中心からの距離
point_dist = Math.sqrt((x - eye[:center][:x]) * (x - eye[:center][:x]) +
(y - eye[:center][:y]) * (y - eye[:center][:y]))
# 目の色からの距離
color_dist = nn_color_dist(p, eye[:color][0 ... 2])
# 重みを計算して色相を回す
dw = gauss(point_dist, eye[:r] * B)
cw = gauss(color_dist, S)
dest.pixel_color(x, y, mulp(p, hsl, [(dw * cw) * A, 1.0].min))
end
end
end
def self.gauss(d, sigma)
Math.exp(-(d * d) / (2.0 * sigma * sigma))
end
def self.mulp(p1, hsl2, w)
hsl1 = p1.to_HSL
hue = Math.atan2((1.0 - w) * Math.sin(hsl1[0] * Math::PI * 2.0) +
w * Math.sin(hsl2[0] * Math::PI * 2.0),
(1.0 - w) * Math.cos(hsl1[0] * Math::PI * 2.0) +
w * Math.cos(hsl2[0] * Math::PI * 2.0)) / (Math::PI * 2.0)
if (hue < 0)
hue = 1.0 + hue
end
#saturation = ((1.0 - w) * hsl1[1] + w * hsl2[1])
saturation = hsl1[1]
Magick::Pixel.from_HSL([hue, saturation, hsl1[2]])
end
def self.nn_color_dist(x, data)
data.reduce(Magick::QuantumRange * 2) do |min_dist, v|
[min_dist,
Math.sqrt((x.red - v.red) ** 2 +
(x.green - v.green) ** 2 +
(x.blue - v.blue) ** 2)
].min
end
end
def self.eye_info(src)
dest = {
:x => src["x"], :y => src["y"],
:w => src["width"], :h => src["height"]
}
dest[:xr] = src["width"] / 2
dest[:yr] = src["height"] / 2
dest[:r] = [dest[:xr], dest[:yr]].max
dest[:center] = {
:x => src["x"] + dest[:xr],
:y => src["y"] + dest[:yr]
}
dest[:color] = src["colors"]
dest
end
end
end
def main(src, dest)
dest ||= "anime.gif"
image = Magick::ImageList.new(src)
gif = Magick::ImageList.new
results = AnimeFace.detect(image)
hue = results.map{ rand }
bg = image.first.copy
bg.delay = 0
gif << bg
10.times do |i|
layer = Magick::Image.new(image.columns, image.rows) do
self.background_color = "none"
end
results.each_index do |j|
hue[j] = hue[j] > 0.9 ? hue[j] + 0.1 - 1.0 : hue[j] + 0.1
AnimeFace::EyeColor.change(bg, results[j],
[hue[j], 0.3, 1.0], layer)
end
layer.delay = (Math.exp((-(i % 5) ** 2 ) / (2.0 * 4.0 ** 2)) * 10).to_i
gif << layer
end
gif.write(dest)
end
if (ARGV[0])
main(ARGV[0], ARGV[1])
else
warn "usage: #{$0} src [dest]"
exit(-1)
end
|
makevoid/animeface-2009
|
animeface-ruby/sample.rb
|
require "pp"
require "rmagick"
require_relative "AnimeFace"
if ARGV.size == 0
warn "Usage: #{$0} <input image>"
exit(-1)
end
image = Magick::ImageList.new(ARGV[0])
output = File.basename(ARGV[0]).split(".").first + "_out.png"
faces = AnimeFace::detect(image)
# when you want to change parameter
#faces = AnimeFace::detect(image, {:step => 2.0, :min_window_size => 24, :threshold => 0.1})
pp faces
gc = Magick::Draw.new
gc.stroke = 'red'
gc.fill = 'transparent'
faces.each do |ctx|
face = ctx["face"]
left_eye = ctx["eyes"]["left"]
right_eye = ctx["eyes"]["right"]
nose = ctx["nose"]
mouth = ctx["mouth"]
chin = ctx["chin"]
hair_color = ctx["hair_color"]
gc.rectangle(face["x"], face["y"], face["x"] + face["width"], face["y"] + face["height"])
gc.rectangle(left_eye["x"], left_eye["y"], left_eye["x"] + left_eye["width"], left_eye["y"] + left_eye["height"])
gc.rectangle(right_eye["x"], right_eye["y"], right_eye["x"] + right_eye["width"], right_eye["y"] + right_eye["height"])
gc.rectangle(nose["x"], nose["y"], nose["x"] + 2, nose["y"] + 2)
gc.rectangle(mouth["x"], mouth["y"], mouth["x"] + mouth["width"], mouth["y"] + mouth["height"])
gc.rectangle(chin["x"], chin["y"], chin["x"] + 2, chin["y"] + 2)
hair_gc = Magick::Draw.new
hair_gc.stroke = 'black'
hair_gc.fill = hair_color.to_color
hair_gc.rectangle(face["x"] + face["width"] + 2, face["y"],
face["x"] + face["width"] + 2 + 16, face["y"] + 16)
hair_gc.draw(image)
score_gc = Magick::Draw.new
score_gc.fill = 'red'
score_gc.stroke = 'transparent'
score_gc.pointsize = 16
score_gc.annotate(image, 0, 0, face["x"], [face["y"]- 2, 0].max, sprintf("%.3f", ctx["likelihood"]))
end
unless faces.empty?
gc.draw(image)
image.write(output)
puts "#{faces.size} faces"
puts "See #{output}"
else
warn "No faces were detected."
end
#result = AnimeFace::detect(image, { :step => 2.0, :min_window_size => 32, :scale_factor => 1.1 })
#pp result
|
makevoid/animeface-2009
|
animeface-ruby/face_collector.rb
|
<gh_stars>100-1000
require "pp"
require "rmagick"
require_relative "AnimeFace"
require "optparse"
require "fileutils"
require "json"
params = ARGV.getopts("", "src:", "dest:", "threshold:", "margin:")
if params["src"].nil? || params["dest"].nil?
warn "usage: #{$0} --src <image dir> --dest <output dir> --threshold <0.0~1.0, default: 0.2> --margin <0.0~, default: 0.1>"
exit(-1)
end
FileUtils.mkdir_p(params["dest"])
threshold = params["threshold"] ? params["threshold"].to_f : 0.2
margin = params["margin"] ? params["margin"].to_f : 0.1
Dir.entries(params["src"]).each do |file|
if file =~ /\.(jpg|png|jpeg)$/i
begin
image = Magick::ImageList.new(File.join(params["src"], file))
faces = AnimeFace::detect(image, {:threshold => threshold})
faces.each do |ctx|
face = ctx["face"]
x = ([face["x"] - face["width"] * margin, 0].max).to_i
y = ([face["y"] - face["height"] * margin, 0].max).to_i
x2 = [x + (face["width"] + face["width"] * margin * 2).to_i, image.columns].min
y2 = [y + (face["height"] + face["height"] * margin * 2).to_i, image.rows].min
if x2 - x != y2 - y
w = [x2 - x, y2 -y].min
x2 = x + w
y2 = y + w
end
crop = image.crop(x, y, x2 - x, y2 - y, true)
crop.write(File.join(params["dest"],
sprintf("%s_%d_%d_%d_%d.png",
File.basename(file).split(".").first,
x, y, x2 - x, y2 - y)))
crop.dispose
end
image.dispose
rescue => e
warn e.message
end
end
end
|
makevoid/animeface-2009
|
animeface-ruby/proc_folder.rb
|
<reponame>makevoid/animeface-2009
require "set"
require 'json'
require "rmagick"
require_relative "AnimeFace"
require "progress_bar"
def get_box(thing)
keys = Set["x", "y", "width", "height"]
return thing.select { |key, value| keys.include? key }
end
if ARGV.size != 2
warn "Usage: #{$0} <dir_path> <output_file>"
exit(-1)
end
dir_path = ARGV[0]
files = Dir["#{dir_path}/*"]
output_file = ARGV[1]
fout = File.open(output_file, "w")
bar = ProgressBar.new(files.length)
files.each do |file|
image = Magick::ImageList.new(file)
faces = AnimeFace::detect(image)
image.destroy!
faces.each_with_index do |ctx, index|
face = ctx["face"]
left_eye = ctx["eyes"]["left"]
right_eye = ctx["eyes"]["right"]
mouth = ctx["mouth"]
likelihood = ctx["likelihood"]
info = {
"file" => file,
"face" => get_box(face),
"left_eye" => get_box(left_eye),
"right_eye" => get_box(right_eye),
"mouth" => get_box(mouth),
"likelihood" => likelihood
}
fout << info.to_json
fout << "\n"
bar.increment!
end
end
|
makevoid/animeface-2009
|
animeface-ruby/proc_folder_parallel.rb
|
<filename>animeface-ruby/proc_folder_parallel.rb
require "set"
require 'json'
require "rmagick"
require_relative "AnimeFace"
require "progress_bar"
require "parallel"
def get_box(thing)
keys = Set["x", "y", "width", "height"]
return thing.select { |key, value| keys.include? key }
end
if ARGV.size != 2
warn "Usage: #{$0} <dir_path> <output_file>"
exit(-1)
end
dir_path = ARGV[0]
files = Dir["#{dir_path}/*"]
output_file = ARGV[1]
infoss = Parallel.map(files, progress: "Processing images...") do |file|
image = Magick::ImageList.new(file)
faces = AnimeFace::detect(image)
image.destroy!
res = faces.map do |ctx|
face = ctx["face"]
left_eye = ctx["eyes"]["left"]
right_eye = ctx["eyes"]["right"]
mouth = ctx["mouth"]
likelihood = ctx["likelihood"]
info = {
"file" => "" + file, # clone string object
"face" => get_box(face),
"left_eye" => get_box(left_eye),
"right_eye" => get_box(right_eye),
"mouth" => get_box(mouth),
"likelihood" => likelihood
}
info
end
end
fout = File.open(output_file, "w")
infoss.flatten(1).each do |info|
fout << info.to_json
fout << "\n"
end
|
makevoid/animeface-2009
|
animeface-ruby/extconf_local.rb
|
require "mkmf"
dir_config("nvxs", "../install/include", "../install/lib")
rpath=File.expand_path(File.join(File.dirname(__FILE__), '../install/lib'))
$LDFLAGS << " -Wl,-rpath,#{rpath}"
unless ( have_header('nv_core.h') && have_library('nvxs', 'nv_matrix_alloc'))
$stderr.puts("error: Can't locate libnvxs")
exit(-1)
end
create_makefile("AnimeFace")
|
makevoid/animeface-2009
|
animeface-ruby/extconf.rb
|
require "mkmf"
dir_config("/usr/local/include", "/usr/local/lib")
unless ( have_header('nv_core.h') && have_library('nvxs', 'nv_matrix_alloc'))
$stderr.puts("error: Can't locate libnvxs")
exit(-1)
end
create_makefile("AnimeFace")
|
makevoid/animeface-2009
|
animeface-ruby/face2xml.rb
|
<filename>animeface-ruby/face2xml.rb<gh_stars>100-1000
require 'rexml/document'
require "optparse"
params = ARGV.getopts("", "face:", "src:", "dest:")
if params["face"].nil? || params["src"].nil?
warn "usage: #{$0} --face <face image dir> --src <image dir> --dest out.xml "
exit(-1)
end
dest = params["dest"] || "out.xml"
src_db = {}
Dir.entries(params["src"]).each do |file|
path = File.join(params["src"], file)
if File.file?(path)
basename = File.basename(file).split(".").first
src_db[basename] = path
end
end
doc = REXML::Document.new
doc << REXML::XMLDecl.new('1.0', 'UTF-8')
root = doc.add_element("dataset")
Dir.entries(params["face"]).each do |file|
path = File.join(params["face"], file)
next unless File.file?(path)
basename = File.basename(file, ".png")
name_parts = basename.split("_")
h = name_parts.pop
w = name_parts.pop
y = name_parts.pop
x = name_parts.pop
src_name = name_parts.join("_")
face = root.add_element("face")
face.add_element("face").add_text(path)
face.add_element("src").add_text(src_db[src_name])
face.add_element("x").add_text(x.to_s)
face.add_element("y").add_text(y.to_s)
face.add_element("width").add_text(w.to_s)
face.add_element("height").add_text(h.to_s)
end
File.open(dest, "w") do |f|
doc.write(f, 2)
end
|
swobspace/devise-remote-user
|
lib/devise_remote_user/controller_behavior.rb
|
module DeviseRemoteUser
module ControllerBehavior
def after_sign_out_path_for(resource_or_scope)
return DeviseRemoteUser.logout_url if remote_user_authenticated? and DeviseRemoteUser.logout_url
super
end
private
def remote_user_authenticated?
DeviseRemoteUser.remote_user_id(request.env).present?
end
end
end
|
swobspace/devise-remote-user
|
lib/devise_remote_user/model.rb
|
<reponame>swobspace/devise-remote-user<gh_stars>1-10
require 'devise_remote_user/strategy'
require 'devise_remote_user/manager'
module Devise::Models
module RemoteUserAuthenticatable
extend ActiveSupport::Concern
included do
def self.find_for_remote_user_authentication(env)
manager = DeviseRemoteUser::Manager.new(self, env)
manager.find_or_create_user
end
end
end
end
|
swobspace/devise-remote-user
|
lib/devise_remote_user/manager.rb
|
<reponame>swobspace/devise-remote-user
module DeviseRemoteUser
#
# The Manager class is responsible for connecting the appliation's User
# class with remote user information in the request environment.
#
class Manager
attr_reader :klass, :env
def initialize(klass, env)
@klass = klass
@env = env
end
def find_or_create_user
user = find_user
if !user && DeviseRemoteUser.auto_create
user = create_user
end
update_user(user) if user && DeviseRemoteUser.auto_update
user
end
def find_user
klass.where(user_criterion).first
end
def create_user
random_password = <PASSWORD>Random.hex(16)
attrs = user_criterion.merge({password: <PASSWORD>, password_confirmation: <PASSWORD>})
klass.create(attrs)
end
def update_user(user)
user.update_attributes(remote_user_attributes)
end
protected
def remote_user_attributes
DeviseRemoteUser.attribute_map.inject({}) { |h, (k, v)| h[k] = env[v] if env.has_key?(v); h }
end
def user_criterion
{auth_key => remote_user_id}
end
def remote_user_id
DeviseRemoteUser.remote_user_id(env)
end
def auth_key
DeviseRemoteUser.auth_key || Devise.authentication_keys.first
end
end
end
|
swobspace/devise-remote-user
|
lib/devise_remote_user/strategy.rb
|
<filename>lib/devise_remote_user/strategy.rb<gh_stars>1-10
require 'devise/strategies/authenticatable'
module Devise
module Strategies
class RemoteUserAuthenticatable < Authenticatable
def valid?
DeviseRemoteUser.remote_user_id(env).present?
end
def authenticate!
resource = mapping.to.find_for_remote_user_authentication(env)
resource ? success!(resource) : fail
end
end
end
end
Warden::Strategies.add(:remote_user_authenticatable, Devise::Strategies::RemoteUserAuthenticatable)
|
swobspace/devise-remote-user
|
spec/dummy/config/routes.rb
|
Dummy::Application.routes.draw do
root to: "application#index"
devise_for :users
end
|
swobspace/devise-remote-user
|
spec/lib/devise_remote_user_spec.rb
|
<reponame>swobspace/devise-remote-user
require 'spec_helper'
describe DeviseRemoteUser do
context ".remote_user_id" do
let(:mock_env) { { 'REMOTE_USER' => 'some-id' } }
context "with a string for the env_key" do
before do
DeviseRemoteUser.env_key = "REMOTE_USER"
end
it "should retrieve the key from the env" do
expect(DeviseRemoteUser.remote_user_id(mock_env)).to eq "some-id"
end
end
context "with a proc for the env_key" do
before do
DeviseRemoteUser.env_key = lambda { |env| "#{env['REMOTE_USER']}@<EMAIL>" }
end
it "should retrieve the key from the env" do
expect(DeviseRemoteUser.remote_user_id(mock_env)).to eq "<EMAIL>"
end
end
end
end
|
swobspace/devise-remote-user
|
spec/dummy/app/models/user.rb
|
class User < ActiveRecord::Base
devise :remote_user_authenticatable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
|
swobspace/devise-remote-user
|
spec/controllers/application_controller_spec.rb
|
<reponame>swobspace/devise-remote-user
require 'spec_helper'
describe ApplicationController do
controller do
def remote_user_name=(user_name)
request.env[DeviseRemoteUser.env_key] = user_name
end
def remote_user_attributes=(attrs)
attrs.each {|k, v| request.env[k] = v }
end
end
after { User.destroy_all }
describe "remote user authentication" do
describe "when remote user exists" do
let(:user) { FactoryGirl.create(:user) }
before { controller.remote_user_name = user.email }
it "should login the remote user" do
get :index
expect(controller.user_signed_in?).to be_true
expect(controller.current_user).to eq(user)
end
end
describe "when remote user is not present" do
before { controller.remote_user_name = nil }
it "should do nothing" do
get :index
expect(controller.user_signed_in?).to be_false
end
end
describe "when remote user does not exist" do
let(:email) { "<EMAIL>" }
before { controller.remote_user_name = email }
describe "and auto-creation is enabled" do
before { allow(DeviseRemoteUser).to receive(:auto_create) { true } }
it "should create and sign in a new user" do
get :index
expect(response).to be_successful
expect(controller.user_signed_in?).to be_true
expect(User.find_by_email(email)).to eq(controller.current_user)
end
end
describe "and auto-creation is disabled" do
before { allow(DeviseRemoteUser).to receive(:auto_create) { false } }
it "should not create a user for the remote user" do
get :index
response.should_not be_successful
controller.user_signed_in?.should be_false
User.find_by_email(email).should be_nil
end
end
end
describe "when a local database user is already signed in" do
let(:local_user) { FactoryGirl.create(:user) }
before do
allow(DeviseRemoteUser).to receive(:auto_create) { true }
controller.remote_user_name = remote_user.email
sign_in local_user
end
describe "and remote user exists" do
let(:remote_user) { FactoryGirl.create(:user) }
it "should not clobber the existing user session" do
get :index
expect(controller.current_user).to eq(local_user)
expect(controller.current_user).not_to eq(remote_user)
end
end
describe "and remote user does not exist" do
let(:remote_user) { FactoryGirl.build(:user) }
it "should not clobber the existing user session" do
get :index
expect(controller.current_user).to eq(local_user)
expect(controller.current_user).not_to eq(remote_user)
expect(User.find_by_email(remote_user.email)).to be_nil
end
end
end
describe "auto-updating user attributes" do
let(:user) { FactoryGirl.create(:user, first_name: 'Hardy', last_name: 'HarHar', nickname: "Laurel's Buddy", display_name: '<NAME>') }
before do
allow(DeviseRemoteUser).to receive(:attribute_map) do
{ first_name: 'givenName',
nickname: 'eduPersonNickname',
last_name: 'sn',
display_name: 'displayName' }
end
end
describe "when auto-creation is disabled" do
before do
allow(DeviseRemoteUser).to receive(:auto_update) { false }
controller.remote_user_name = user.email
controller.remote_user_attributes = {
'givenName' => 'Fleece',
'sn' => 'Vest',
'eduPersonNickname' => 'Iconoclast',
'displayName' => '<NAME> (Iconoclast)'
}
end
it "should not update the user attributes" do
get :index
user.reload
expect(user.first_name).to eq('Hardy')
expect(user.last_name).to eq('HarHar')
expect(user.display_name).to eq('<NAME>')
expect(user.nickname).to eq("Laurel's Buddy")
end
end
describe "when auto-creation is enabled" do
before do
allow(DeviseRemoteUser).to receive(:auto_update) { true }
controller.remote_user_attributes = {
'givenName' => 'Fleece',
'sn' => 'Vest',
'eduPersonNickname' => 'Iconoclast',
'displayName' => '<NAME> (Iconoclast)'
}
end
describe "and database authentication wins" do
before { sign_in user }
it "should not update the user attributes" do
get :index
user.reload
expect(user.first_name).to eq('Hardy')
expect(user.last_name).to eq('HarHar')
expect(user.display_name).to eq('<NAME>')
expect(user.nickname).to eq("Laurel's Buddy")
end
end
describe "and remote user authentication wins" do
before do
controller.remote_user_name = user.email
controller.remote_user_attributes = {
'givenName' => 'Fleece',
'sn' => 'Vest',
'eduPersonNickname' => 'Iconoclast',
'displayName' => '<NAME> (Iconoclast)'
}
end
it "should update the user attributes" do
get :index
user.reload
expect(user.first_name).to eq('Fleece')
expect(user.last_name).to eq('Vest')
expect(user.display_name).to eq('<NAME> (Iconoclast)')
expect(user.nickname).to eq('Iconoclast')
end
end
end
end
end
end
|
swobspace/devise-remote-user
|
lib/devise_remote_user.rb
|
require 'devise'
require 'devise_remote_user/engine'
require 'devise_remote_user/controller_behavior'
module DeviseRemoteUser
# request.env key for remote user name
# Set to 'HTTP_REMOTE_USER' in config/initializers/devise.rb if behind reverse proxy
mattr_accessor :env_key
@@env_key = 'REMOTE_USER'
# Enable user auto-creation of user from remote user attributes
mattr_accessor :auto_create
@@auto_create = false
# Enable user auto-update of user attributes from remote user attributes
mattr_accessor :auto_update
@@auto_update = false
# User attribute used for lookup of remote user
# Defaults to Devise.authentication_keys.first
mattr_accessor :auth_key
@@auth_key = nil
# Map of User model attributes to request.env keys for updating a local user when auto-creation is enabled.
mattr_accessor :attribute_map
@@attribute_map = {}
# Settings for redirecting to the remote user logout URL
# Enable by including DeviseRemoteUser::Controllers::Helpers in ApplicationController
# (it overrides Devise's after_sign_out_path_for method).
mattr_accessor :logout_url
@@logout_url = '/'
# make User model configurable i.e. for usage in rails engines
mattr_accessor :user_model
@@user_model = 'User'
def self.configure
yield self
end
def self.remote_user_id env
case env_key
when Proc
env_key.call(env)
else
env[env_key]
end
end
def self.user_model
@@user_model.constantize
end
end
Devise.add_module(:remote_user_authenticatable,
:strategy => true,
:controller => :sessions,
:model => 'devise_remote_user/model')
|
plainlystated/rvm
|
libraries/resource_rvm_ruby.rb
|
require 'chef/resource/lwrp_base'
class Chef
class Resource
class RvmRuby < Chef::Resource::LWRPBase
provides :rvm_ruby
self.resource_name = :rvm_ruby
actions :install
default_action :install
end
end
end
|
plainlystated/rvm
|
libraries/provider_rvm_ruby.rb
|
<reponame>plainlystated/rvm<gh_stars>0
require 'chef/provider/lwrp_base'
class Chef
class Provider
class RvmRuby < Chef::Provider::LWRPBase
provides :rvm_ruby if defined?(provides)
use_inline_resources if defined?(use_inline_resources)
def whyrun_supported?
true
end
action :install do
remote_file 'rvm_installer' do
path "#{Chef::Config[:file_cache_path]}/rvm_installer.sh"
source node['rvm']['installer_url']
mode 0755
not_if { ::File.exists?("#{Chef::Config[:file_cache_path]}/rvm_installer.sh") }
action :create
end
end
end
end
end
|
plainlystated/rvm
|
metadata.rb
|
name 'rvm'
maintainer '<NAME>'
maintainer_email '<EMAIL>'
license 'Apache-2.0'
description 'Manages system-wide and per-user RVMs and manages installed Rubies via Chef Resources.'
long_description "Please refer to README.md (it's long)."
version '0.10.1'
source_url 'https://github.com/martinisoft/chef-rvm'
issues_url 'https://github.com/martinisoft/chef-rvm/issues'
chef_version '>= 12.9' if respond_to?(:chef_version)
%w(amazon centos redhat scientific oracle fedora debian ubuntu).each do |os|
supports os
end
|
jaico/Sttarter
|
Sttarter.podspec
|
<gh_stars>0
Pod::Spec.new do |s|
s.name = 'Sttarter'
s.version = '0.1.8'
s.summary = 'By far the most Sttarter I have seen in my entire life. No joke.'
s.description = <<-DESC
This Sttarter changes its dependancy gradually makes your app look fantastic!
DESC
s.homepage = 'https://github.com/jaico/Sttarter.git'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<Jaico>' => '<<EMAIL>>' }
s.source = { :git => 'https://github.com/jaico/Sttarter.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.swift_version = '3.0'
s.source_files = 'Sttarter/Sttarter.framework'
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/quick_replies.rb
|
require_relative '../strings'
require_relative '../bot'
Dir[File.join(__dir__, './quick_replies_strings', '*')].each { |file| require file }
class MessengerBot
QUICK_REPLIES = {
"en" => QUICK_REPLY_EN,
"ta" => QUICK_REPLY_TA
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
subscription/subscription.rb
|
require 'facebook/messenger'
require 'httparty'
require 'json'
require_relative './subscription_template'
require_relative '../facebookBot/bot'
require_relative '../models/vaccination_schedule'
require_relative '../database_editors/vaccination_schedule_editor'
require_relative './subscription_strings'
class SubscriptionClass
#Method to handle subscriptions
def subscriptions(id)
@language = MessengerBot.new.get_language(id)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if user != nil then
subscriptions = user.subscription
if subscriptions == true then
show_unsubscribe(id)
else
show_subscribe(id)
end
else
VaccinationScheduleEditor.new.add_new_kid(id," ","",Date.today)
MessengerBot.say(id,"Please register your details first!")
# MessengerBot.initial_config(id)
end
end
#Show Subscription Template
def show_subscribe(id)
message_option = SUBSCRIPTION_MESSAGE_OPTION
message_option[:recipient][:id] = id
message_option[:message][:attachment][:payload][:elements][0][:buttons][0][:title] = SUBSCRIBE_BUTTON["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:buttons][1][:title] = WHY_SUBSCRIBE_BUTTON["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:title] = SUBSCRIPTION_TEXT["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:subtitle] = SHOW_SUBSCRIBE_SUBTITLE_TEXT["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:buttons][0][:payload] = "SUBSCRIBE"
res = HTTParty.post(FB_MESSAGE, headers: HEADER, body: message_option.to_json)
end
#Show Unsubscribe Template
def show_unsubscribe(id)
message_option = SUBSCRIPTION_MESSAGE_OPTION
message_option[:recipient][:id] = id
message_option[:message][:attachment][:payload][:elements][0][:buttons][0][:title] = UNSUBSCRIBE_BUTTON["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:buttons][1][:title] = WHY_SUBSCRIBE_BUTTON["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:title] = SUBSCRIPTION_TEXT["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:subtitle] = SHOW_UNSUBSCRIBE_SUBTITLE_TEXT["#{@language}"]
message_option[:message][:attachment][:payload][:elements][0][:buttons][0][:payload] = "UNSUBSCRIBE"
res = HTTParty.post(FB_MESSAGE, headers: HEADER, body: message_option.to_json)
end
#Add subscription for user to Vaccine reminder
def subscribe(id)
language = MessengerBot.new.get_language(id)
user=VaccinationSchedule.find_by_parent_facebook_userid(id)
user.update_attributes( :subscription => true )
MessengerBot.say(id,SUCCESSFULLY_SUBSCRIBED_TEXT1["#{language}"])
MessengerBot.say(id,SUCCESSFULLY_SUBSCRIBED_TEXT2["#{language}"])
end
#unsubscribe a User from Vaccine reminder
def unsubscribe(id)
language = MessengerBot.new.get_language(id)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
user.update_attributes( :subscription => false )
MessengerBot.say(id, SUCCESSFULLY_UNSUBSCRIBED_TEXT["#{language}"])
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/bot.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
require 'facebook/messenger'
require 'httparty'
require 'json'
require 'date'
require './models/default_vaccine_schedule'
require './models/vaccination_schedule'
require_relative '../utils'
require_relative '../database_editors/vaccination_schedule_editor'
require_relative '../database_editors/fetch_vaccination_details'
require_relative '../database_editors/profile_editor'
require_relative '../database_editors/vaccine_details'
require_relative '../subscription/subscription'
require_relative '../wit/get_wit_message'
require_relative 'json_templates/greeting'
require_relative 'json_templates/persistent_menu'
require_relative 'json_templates/get_started'
require_relative 'json_templates/template'
require_relative 'json_templates/quick_replies'
require_relative 'strings'
include Facebook::Messenger
class MessengerBot
# Method to get user Facebook profile details
def self.get_profile(id)
fb_profile_url = FB_PROFILE + id + FB_PROFILE_FIELDS
profile_details = HTTParty.get(fb_profile_url)
@first_name = profile_details["first_name"]
@last_name = profile_details["last_name"]
@profile_pic = profile_details["profile_pic"]
@locale = profile_details["locale"]
@gender = profile_details["gender"]
return profile_details
end
# Returns language of the user
def get_language(id)
fb_profile_url = FB_PROFILE + id + FB_PROFILE_FIELDS
profile_details = HTTParty.get(fb_profile_url)
locale = profile_details["locale"]
language = locale[0,2]
return language
end
# Method to push a message to Facebook
def self.say(recipient_id, text)
message_options = {
messaging_type: "RESPONSE",
recipient: { id: recipient_id },
message: { text: text }
}
HTTParty.post(FB_MESSAGE, headers: HEADER, body: message_options)
end
# To send a quick reply to user
def self.send_quick_reply(id)
get_profile(id)
@language = @locale[0,2]
message_options = {
messaging_type: "RESPONSE",
recipient: { id: id},
message: {
text: QUICK_REPLY_HEADER["#{@language}"],
quick_replies: QUICK_REPLIES["#{@language}"]
}
}
response = HTTParty.post(FB_MESSAGE, headers: HEADER, body: message_options.to_json)
Bot.on :message do |message|
id = message.sender["id"]
call_message(id,message.text)
end
Bot.on :postback do |postback|
id = postback.sender["id"]
call_postback(id,postback.payload)
end
end
def self.send_terms_and_condition(id)
terms_and_condition_message = TERMS_AND_CONDITION
message_options = {
messaging_type: "RESPONSE",
recipient: { id: id },
message: terms_and_condition_message,
}
HTTParty.post(FB_MESSAGE,headers: HEADER, body: message_options.to_json)
end
# Typing indication:
def self.typing_on(id)
message_options = {
messaging_type: "RESPONSE",
recipient: { id: id },
sender_action: "typing_on",
}
response = HTTParty.post(FB_MESSAGE,headers: HEADER, body: message_options.to_json)
end
# Initial configuration method to get kid name
def self.initial_config(id)
say(id,ASK_KID_NAME["#{@language}"])
Bot.on :message do |message|
kid_name = message.text
get_dob(id,kid_name)
end
end
# Initial configuration method to get kid Date of birth
def self.get_dob(id,kid_name)
say(id,ASK_DOB_TEXT["#{@language}"])
Bot.on :message do |message|
kid_dob = message.text
begin
dob = Date.parse kid_dob
rescue ArgumentError
say(id,INVALID_DOB_ERROR_TEXT["#{@language}"])
get_dob(id,kid_name)
end
if dob !=nil then
date_full_format = dob.strftime("%d %b %Y")
reply_text = GOT_IT_TEXT["#{@language}"] + "#{date_full_format}"
say(id,reply_text)
get_gender(id,kid_name,dob)
end
end
end
# Initial configuration method to get kid Gender
def self.get_gender(id,kid_name,kid_dob)
say(id,ASK_KID_GENDER["#{@language}"])
Bot.on :message do |message|
if((message.text).downcase == BOY_TEXT["#{@language}"] || (message.text).downcase == MALE_TEXT["#{@language}"] ) then
kid_gender = "male"
elsif ((message.text).downcase == GIRL_TEXT["#{@language}"] || (message.text).downcase == FEMALE_TEXT["#{@language}"]) then
kid_gender = "female"
else
say(id,INVALID_GENDER_ERROR_TEXT["#{@language}"])
get_gender(id,kid_name,kid_dob)
end
if kid_gender !=nil then
VaccinationScheduleEditor.new.add_new_kid(id,kid_name,kid_gender,kid_dob)
say(id,REGISTERATION_SUCCESSFULL_TEXT["#{@language}"])
send_quick_reply(id)
end
end
end
# Method to edit kid name in the database
def self.edit_kid_name(id,kid_name =nil)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if kid_name == nil then
say(id,ASK_KID_NAME["#{@language}"])
Bot.on :message do |message|
user.update_attributes(:kid_name => message.text)
reply_text = KID_NAME_UPDATED_TEXT["#{@language}"] + "#{message.text}!"
say(id,reply_text)
send_quick_reply(id)
end
else
user.update_attributes(:kid_name => kid_name)
reply_text = KID_NAME_UPDATED_TEXT["#{@language}"] + "#{kid_name}"
say(id,reply_text)
send_quick_reply(id)
end
end
# Method to edit kid gender in the database
def self.edit_kid_gender(id)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
say(id,ASK_KID_GENDER["#{@language}"])
Bot.on :message do |message|
if((message.text).downcase == BOY_TEXT["#{@language}"] || (message.text).downcase == MALE_TEXT["#{@language}"] ) then
kid_gender = "male"
elsif ((message.text).downcase == GIRL_TEXT["#{@language}"] || (message.text).downcase == FEMALE_TEXT["#{@language}"]) then
kid_gender = "female"
else
say(id,INVALID_GENDER_ERROR_TEXT["#{@language}"])
edit_kid_gender(id,)
end
if kid_gender !=nil then
user.update_attributes(:kid_gender => kid_gender)
say(id,KID_GENDER_UPDATED_TEXT["#{@language}"])
send_quick_reply(id)
end
end
end
# Method to edit kid date of birth in the database
def self.edit_kid_dob(id,dob_val = nil)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if dob_val == nil then
say(id,ASK_DOB_TEXT["#{@language}"])
Bot.on :message do |message|
kid_dob = message.text
validate_dob(id,kid_dob)
end
else
validate_dob(id,dob_val)
end
end
# Method to validate kid date of birth
def self.validate_dob(id,kid_dob)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
begin
dob = Date.parse kid_dob
rescue ArgumentError
say(id,INVALID_DOB_ERROR_TEXT["#{@language}"])
edit_kid_dob(id)
end
if dob !=nil then
date_full_format = dob.strftime("%d %b %Y")
say(id,"Got it, #{date_full_format}")
user.update_attributes(:kid_dob => kid_dob)
VaccinationScheduleEditor.new.update_kid_record(id,dob)
say(id,KID_DOB_UPDATED_TEXT["#{@language}"])
send_quick_reply(id)
end
end
# Method used to retrive the user profile when rejoin to the bot
def old_user(id)
MessengerBot.say(id,OLD_USER_GREETING_CONTENT["#{@language}"])
ProfileEditor.new.get_parent_profile(id)
MessengerBot.send_quick_reply(id)
end
# Initial configuration for the bot
Facebook::Messenger::Subscriptions.subscribe(access_token: ENV["FB_ACCESS_TOKEN"],
subscribed_fields: %w[messages feed mention name messaging_postbacks])
greeting_response =HTTParty.post(FB_PAGE, headers: HEADER, body: GREETING.to_json )
get_started_response =HTTParty.post(FB_PAGE, headers: HEADER, body: GET_STARTED.to_json)
persistent_menu_response =HTTParty.post(FB_PAGE, headers: HEADER, body: PERSISTENT_MENU.to_json)
# Triggers whenever a message has got
Bot.on :message do |message|
id = message.sender["id"]
call_message(id,message.text)
end
# Triggers whenever a postback happens
Bot.on :postback do |postback|
id = postback.sender["id"]
call_postback(id,postback.payload)
end
# Method to handle bot messages
def self.call_message(id,message_text)
typing_on(id)
get_profile(id)
@language = @locale[0,2]
case message_text.downcase
when "hi"
hi_message_reply_text = GREETING_MESSAGE_SALUTATION["#{@language}"] + "#{@first_name} #{@last_name}! " + HI_MESSAGE_CONTENT["#{@language}"]
say(id,hi_message_reply_text)
send_quick_reply(id)
when UPCOMING_VACCINATION_MESSAGE_TEXT["#{@language}"]
FetchVaccinationDetails.new.upcoming(id)
when PREVIOUS_VACCINATION_MESSAGE_TEXT["#{@language}"]
FetchVaccinationDetails.new.previous(id)
when PROFILE_MESSAGE_TEXT["#{@language}"]
ProfileEditor.new.get_parent_profile(id)
when EDIT_KID_NAME_TEXT["#{@language}"]
MessengerBot.edit_kid_name(id)
when EDIT_KID_DOB_TEXT["#{@language}"]
MessengerBot.edit_kid_dob(id)
when EDIT_KID_GENDER_TEXT["#{@language}"]
MessengerBot.edit_kid_gender(id)
else
handle_wit_response(id,message_text)
end
end
#Method to handle wit response
def self.handle_wit_response(id,message_text)
wit_response = Wit.new.get_intent(message_text)
if wit_response.class == String
MessengerBot.call_postback(id,wit_response)
else
if wit_response["gender_value"] != nil then
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if wit_response["gender_value"][0]["value"] == "MALE" then
user.update_attributes(:kid_gender => "male")
say(id,KID_GENDER_UPDATED_TEXT["#{@language}"])
send_quick_reply(id)
elsif wit_response["gender_value"][0]["value"] == "FEMALE" then
user.update_attributes(:kid_gender => "female")
say(id,KID_GENDER_UPDATED_TEXT["#{@language}"])
send_quick_reply(id)
else
MessengerBot.call_postback(id,wit_response["intent"][0]["value"])
end
end
if wit_response["dob_value"] !=nil then
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
edit_kid_dob(id,wit_response["dob_value"][0]["value"])
end
if wit_response["name_value"] != nil then
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
edit_kid_name(id,wit_response["name_value"][0]["value"])
end
if wit_response["vaccine"] !=nil then
VaccineDetails.new.get_vaccine_details(id,wit_response["vaccine"][0]["value"])
end
end
end
#Method to handle postbacks
def self.call_postback(id,postback_payload)
typing_on(id)
get_profile(id)
@language = @locale[0,2]
case postback_payload
when "GET_STARTED"
get_profile(id)
greeting_text = GREETING_MESSAGE_SALUTATION["#{@language}"] + "#{@first_name} #{@last_name}! " + GREETING_MESSAGE_CONTENT["#{@language}"]
say(id,greeting_text)
send_terms_and_condition(id)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if user == nil then
initial_config(id)
else
MessengerBot.new.old_user(id)
end
when "UPCOMING_VACCINATIONS"
FetchVaccinationDetails.new.upcoming(id)
when "PREVIOUS_VACCINATIONS"
FetchVaccinationDetails.new.previous(id)
when "PROFILE"
ProfileEditor.new.get_parent_profile(id)
when "SUBSCRIPTION"
SubscriptionClass.new.subscriptions(id)
when "SUBSCRIBE"
SubscriptionClass.new.subscribe(id)
when "UNSUBSCRIBE"
SubscriptionClass.new.unsubscribe(id)
when "WHY_SUBSCRIBE"
say(id, WHY_SUBSCRIBE_TEXT["#{@language}"])
when "EDIT_KID_NAME"
MessengerBot.edit_kid_name(id)
when "EDIT_KID_GENDER"
MessengerBot.edit_kid_gender(id)
when "EDIT_KID_DOB"
MessengerBot.edit_kid_dob(id)
when "HI"
hi_message_reply_text = GREETING_MESSAGE_SALUTATION["#{@language}"] + "#{@first_name} #{@last_name}! " + HI_MESSAGE_CONTENT["#{@language}"]
say(id,hi_message_reply_text)
send_quick_reply(id)
else
say(id, COULDNOT_UNDERSTAND_THE_MESSAGE_TEXT["#{@language}"])
say(id, HELP_TEXT["#{@language}"])
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/quick_replies_strings/quick_replies_ta.rb
|
class MessengerBot
QUICK_REPLY_TA = [
{
"content_type": 'text',
"title": UPCOMING_VACCINATION_MESSAGE_TEXT["ta"] ,
"payload": "UPCOMING_VACCINATIONS"
},
{
"content_type": 'text',
"title": PREVIOUS_VACCINATION_MESSAGE_TEXT["ta"],
"payload": "PREVIOUS_VACCINATIONS"
},
]
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
subscription/subscription_template.rb
|
class SubscriptionClass
SUBSCRIPTION_MESSAGE_OPTION = {
"messaging_type": "RESPONSE",
"recipient": { "id": "0" },
"message":{
"attachment":{
"type": 'template',
"payload":{
"template_type": "generic",
"elements":[
{
"title": "Subscription",
"subtitle": "You are now Unsubscribed!",
"buttons":[
{
"type": "postback",
"title": "Subscribe",
"payload": "SUBSCRIBE"
},
{
"type": "postback",
"title": "Why Subscribe?",
"payload": "WHY_SUBSCRIBE"
}
]
}
]
}
}
}
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/display_vaccination_dates.rb
|
require 'facebook/messenger'
require 'httparty'
require 'json'
require_relative './bot.rb'
require_relative 'json_templates/template'
require_relative '../utils'
class MessengerBot
#Display upcoming and previous vaccination dates and their details
def display_vaccination_dates(id,vaccination_dates)
template = GENERIC_TEMPLATE_BODY
elements = []
@language = MessengerBot.new.get_language(id)
# if vaccination_dates.length == 0 then
# MessengerBot.say(id,"No vaccines available")
# end
for i in 0..9
break if i > vaccination_dates.length-1
vaccine_name = vaccination_dates[i][:vaccine_name]
vaccine_date = Date.parse(vaccination_dates[i][:due_date]).strftime("%d %b %Y")
vaccine_url = vaccination_dates[i][:url]
new_element = {
"title": "#{vaccine_name.upcase}",
"subtitle": "#{DUE_DATE["#{@language}"]}: #{vaccine_date}",
"buttons":[
{
"type": "web_url",
"title": DETAILS_BUTTON["#{@language}"],
"url": "#{vaccine_url}"
}
]
}
elements << new_element
end
template[:attachment][:payload][:elements] = elements
message_options = {
"messaging_type": "RESPONSE",
"recipient": { "id": "#{id}"},
"message": "#{template.to_json}"
}
res = HTTParty.post(FB_MESSAGE, headers: HEADER, body: message_options)
Bot.on :message do |message|
id = message.sender["id"]
MessengerBot.call_message(id,message.text)
end
Bot.on :postback do |postback|
id = postback.sender["id"]
MessengerBot.call_postback(id,postback.payload)
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/quick_replies_strings/quick_replies_en.rb
|
class MessengerBot
QUICK_REPLY_EN = [
{
"content_type": 'text',
"title": UPCOMING_VACCINATION_MESSAGE_TEXT["en"] ,
"payload": "UPCOMING_VACCINATIONS"
},
{
"content_type": 'text',
"title": PREVIOUS_VACCINATION_MESSAGE_TEXT["en"],
"payload": "PREVIOUS_VACCINATIONS"
},
]
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
database_editors/profile_editor.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder<filename>database_editors/profile_editor.rb
require 'date'
require 'sinatra/activerecord'
require_relative '../facebookBot/display_vaccination_dates'
require_relative './vaccination_schedule_editor'
require_relative '../facebookBot/bot.rb'
require_relative '../facebookBot/display_profile'
require './models/default_vaccine_schedule'
require './models/vaccination_schedule'
class ProfileEditor
#Method to fetch User profile from database
def get_parent_profile(id)
@language = MessengerBot.new.get_language(id)
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if user != nil then
parent_first_name = user.parent_first_name
parent_last_name = user.parent_last_name
kid_name = user.kid_name
kid_dob = user.kid_dob
kid_gender = user.kid_gender
MessengerBot.new.display_profile(id,parent_first_name,parent_last_name,kid_name,kid_dob,kid_gender)
else
VaccinationScheduleEditor.new.add_new_kid(id," "," ",Date.today)
MessengerBot.say(id,ASK_TO_REGISTER_TEXT["#{@language}"])
end
Bot.on :message do |message|
id = message.sender["id"]
MessengerBot.call_message(id,message.text)
end
Bot.on :postback do |postback|
id = postback.sender["id"]
MessengerBot.call_postback(id,postback.payload)
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/persistent_menu.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder<filename>facebookBot/json_templates/persistent_menu.rb
require_relative "../strings"
Dir[File.join(__dir__, './persistent_menu_strings', '*')].each { |file| require file }
class MessengerBot
PERSISTENT_MENU = {
"persistent_menu": [
PERSISTENT_MENU_DEFAULT,
PERSISTENT_MENU_TA
]
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/persistent_menu_strings/persistent_menu_ta.rb
|
<gh_stars>1-10
require_relative "../../strings"
class MessengerBot
PERSISTENT_MENU_TA = {
"locale": "ta_IN",
"composer_input_disabled": false,
"call_to_actions": [{
"title": "💉 #{UPCOMING_VACCINATION_DETAILS_BUTTON["ta"]}",
"type": "postback",
"payload": "UPCOMING_VACCINATIONS"
},
{
"title": "💉 #{PREVIOUS_VACCINATION_DETAILS_BUTTON["ta"]}",
"type": "postback",
"payload": "PREVIOUS_VACCINATIONS"
},
{
"title": "🔧 #{MORE_BUTTON["ta"]}",
"type": "nested",
"call_to_actions": [{
"title": "🔔 #{SUBSCRIPTION_BUTTON["ta"]}",
"type": "postback",
"payload": "SUBSCRIPTION"
},
{
"title": "👤 #{PROFILE_BUTTON["ta"]}",
"type": "postback",
"payload": "PROFILE"
}]
}]
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
database_editors/vaccine_details.rb
|
require 'date'
require 'sinatra/activerecord'
require 'facebook/messenger'
require_relative '../facebookBot/display_vaccination_dates'
require './models/default_vaccine_schedule'
require './models/vaccination_schedule'
require_relative './db_strings'
class VaccineDetails
def get_vaccine_details(id,vaccine_name)
@language = MessengerBot.new.get_language(id)
vaccine = DefaultVaccineSchedule.select("*").where("vaccine_name LIKE ?","#{vaccine_name.downcase}%")
if vaccine.length == 0
reply_text = NO_VACCINE_FOUND_TEXT["#{@language}"] + vaccine_name + CHECK_OUT_SPELLING_TEXT["#{@language}"]
MessengerBot.say(id, reply_text)
else
kid = VaccinationSchedule.find_by_parent_facebook_userid(id)
vaccine_list =[]
vaccine.each do |v|
new_vaccine ={
"vaccine_name": v.vaccine_name,
"due_date": "#{kid.kid_dob+v.due_date}",
"url": v.url
}
vaccine_list<<new_vaccine
end
MessengerBot.new.display_vaccination_dates(id,vaccine_list)
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/display_profile.rb
|
require 'facebook/messenger'
require 'httparty'
require 'json'
require_relative './bot.rb'
require_relative 'json_templates/template'
require_relative '../utils'
class MessengerBot
# Method to display user profile details
def display_profile(id,parent_first_name,parent_last_name,kid_name,kid_dob,kid_gender)
template = GENERIC_TEMPLATE_BODY
elements = []
@language = MessengerBot.new.get_language(id)
new_element = {
"title": "👤 #{PROFILE_BUTTON["#{@language}"]}",
"subtitle": "#{YOUR_NAME["#{@language}"]}: #{parent_first_name}\n#{YOUR_KID_NAME["#{@language}"]}: #{kid_name}\n#{KID_DOB["#{@language}"]}: #{kid_dob}\n#{KID_GENDER["#{@language}"]}: #{kid_gender}",
"buttons":[
{
"type": "postback",
"title": "👶 #{EDIT_KID_NAME_TEXT["#{@language}"]}",
"payload": "EDIT_KID_NAME"
},
{
"type": "postback",
"title": "📅 #{EDIT_KID_DOB_TEXT["#{@language}"]}",
"payload": "EDIT_KID_DOB"
},
{
"type": "postback",
"title": "🚻 #{EDIT_KID_GENDER_TEXT["#{@language}"]}",
"payload": "EDIT_KID_GENDER"
}
]
}
elements << new_element
template[:attachment][:payload][:elements] = elements
message_options = {
"messaging_type": "RESPONSE",
"recipient": { "id": "#{id}"},
"message": "#{template.to_json}"
}
res = HTTParty.post(FB_MESSAGE, headers: HEADER, body: message_options)
Bot.on :message do |message|
id = message.sender["id"]
MessengerBot.call_message(id,message.text)
end
Bot.on :postback do |postback|
id = postback.sender["id"]
MessengerBot.call_postback(id,postback.payload)
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/template.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
class MessengerBot
GENERIC_TEMPLATE_BODY = {
"attachment": {
"type": "template",
"payload":{
"template_type": "generic",
"elements":[{
"title": "",
"subtitle": "",
"buttons":[{
"type": "",
"title": "",
"payload": ""
}]
}]
}
}
}
TERMS_AND_CONDITION ={
"attachment":{
"type": "template",
"payload":{
"template_type": "button",
"text": "To know about Terms and Condition,",
"buttons": [{
"type": "web_url",
"title": "Terms and Condition",
"url": "https://smart-vaccine-reminder.herokuapp.com/terms&conditions"
},
{
"type": "web_url",
"title": "Privacy Policy",
"url": "https://smart-vaccine-reminder.herokuapp.com/privacy-policy"
}]
}
}
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
app.rb
|
require 'sinatra'
require 'sinatra/activerecord'
require 'rake'
require 'dotenv/load'
# Talk to Facebook
get '/webhook' do
params['hub.challenge'] if ENV["VERIFY_TOKEN"] == params['hub.verify_token']
end
#Show the home page
get "/" do
send_file 'index.html'
end
#Show the terms and conditions page
get "/termsandconditions" do
"Terms and conditions page here"
end
#Show the privacy polic page
get "/privacy-policy" do
"Privacy Policy"
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/get_started.rb
|
class MessengerBot
GET_STARTED = {
"get_started":{
"payload": "GET_STARTED"
}
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/persistent_menu_strings/persistent_menu_en.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
require_relative "../../strings"
class MessengerBot
PERSISTENT_MENU_DEFAULT = {
"locale": "default",
"composer_input_disabled": false,
"call_to_actions": [{
"title": "💉 #{UPCOMING_VACCINATION_DETAILS_BUTTON["en"]}",
"type": "postback",
"payload": "UPCOMING_VACCINATIONS"
},
{
"title": "💉 #{PREVIOUS_VACCINATION_DETAILS_BUTTON["en"]}",
"type": "postback",
"payload": "PREVIOUS_VACCINATIONS"
},
{
"title": "🔧 #{MORE_BUTTON["en"]}",
"type": "nested",
"call_to_actions": [{
"title": "🔔 #{SUBSCRIPTION_BUTTON["en"]}",
"type": "postback",
"payload": "SUBSCRIPTION"
},
{
"title": "👤 #{PROFILE_BUTTON["en"]}",
"type": "postback",
"payload": "PROFILE"
}]
}]
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
database_editors/fetch_vaccination_details.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
require 'date'
require 'sinatra/activerecord'
require 'facebook/messenger'
require_relative '../facebookBot/display_vaccination_dates'
require './models/default_vaccine_schedule'
require './models/vaccination_schedule'
require_relative './db_strings'
class FetchVaccinationDetails
VACCINE_COLUMNS_INDEX_STARTS_AT = 10
#Method to fetch upcoming vaccination days from database
def upcoming(id)
@language = MessengerBot.new.get_language(id)
columns = VaccinationSchedule.column_names
today = Date.today
upcoming_vaccine = []
for i in VACCINE_COLUMNS_INDEX_STARTS_AT..columns.length-1
user = VaccinationSchedule.select("#{columns[i]}").where("#{columns[i]} > ? AND parent_facebook_userid = ?",today,id).to_a
default_record = DefaultVaccineSchedule.where("vaccine_name = ?",columns[i])
if user.any? then
new_vaccine_date = user[0]["#{columns[i]}"]
vaccine_url = default_record[0]["url"]
new_vaccine ={
"vaccine_name": "#{columns[i]}",
"due_date": "#{new_vaccine_date}",
"url": "#{vaccine_url}"
}
upcoming_vaccine << new_vaccine
end
end
if upcoming_vaccine.length > 0 then
MessengerBot.say(id,LIST_OF_UPCOMING_VACCINES_TEXT["#{@language}"])
MessengerBot.new.display_vaccination_dates(id,upcoming_vaccine)
else
MessengerBot.say(id,ALL_VACCINES_PROVIDED_MESSAGE_TEXT["#{@language}"])
end
Bot.on :message do |message|
id = message.sender["id"]
MessengerBot.call_message(id,message.text)
end
Bot.on :postback do |postback|
id = postback.sender["id"]
MessengerBot.call_postback(id,postback.payload)
end
end
#Method to fetch past vaccination dates from database
def previous(id)
@language = MessengerBot.new.get_language(id)
columns = VaccinationSchedule.column_names
today = Date.today
previous_vaccine = []
for i in VACCINE_COLUMNS_INDEX_STARTS_AT..columns.length-1
user = VaccinationSchedule.select("#{columns[i]}").where("#{columns[i]} < ? AND parent_facebook_userid = ?",today,id).to_a
default_record = DefaultVaccineSchedule.where("vaccine_name = ?",columns[i])
if user.any? then
new_vaccine_date = user[0]["#{columns[i]}"]
vaccine_url = default_record[0]["url"]
new_vaccine ={
"vaccine_name": "#{columns[i]}",
"due_date": "#{new_vaccine_date}",
"url": "#{vaccine_url}"
}
previous_vaccine.insert(0,new_vaccine)
end
end
if previous_vaccine.length > 0 then
MessengerBot.say(id,LIST_OF_PROVIDED_VACCINES_TEXT["#{@language}"])
MessengerBot.new.display_vaccination_dates(id,previous_vaccine)
else
MessengerBot.say(id,REGISTERED_WITH_FUTURE_DATE_TEXT["#{@language}"])
end
Bot.on :message do |message|
id = message.sender["id"]
MessengerBot.call_message(id,message.text)
end
Bot.on :postback do |postback|
id = postback.sender["id"]
MessengerBot.call_postback(id,postback.payload)
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
db/migrate/20180124144808_create_vaccination_schedule.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
#Database table to store the vaccination schedule
class CreateVaccinationSchedule < ActiveRecord::Migration[5.1]
def up
create_table :vaccination_schedules do |t|
# facebook profile details:
t.string :parent_facebook_userid
t.string :parent_first_name
t.string :parent_last_name
t.string :parent_gender
t.string :locale
t.boolean :subscription
# kid details:
t.string :kid_name
t.date :kid_dob
t.string :kid_gender
# list of vaccines to be provided:
t.date :bcg_dose1
t.date :hepb_dose1
t.date :poliovirus_dose1
t.date :hepb_dose2
t.date :poliovirus_dose2
t.date :dtp_dose1
t.date :hib_dose1
t.date :pcv_dose1
t.date :rv_dose1
t.date :poliovirus_dose3
t.date :dtp_dose2
t.date :hib_dose2
t.date :pcv_dose2
t.date :rv_dose2
t.date :hepb_dose3
t.date :dtp_dose3
t.date :hib_dose3
t.date :pcv_dose3
t.date :rv_dose3
t.date :typhoid_dose1
t.date :mmr_dose1
t.date :dtp_dose4
t.date :hib_dose4
t.date :pcv_dose4
t.date :varicella_dose1
t.date :hepa_dose1
t.date :mmr_dose2
t.date :varicella_dose2
t.date :hepa_dose2
t.date :typhoid_dose2
t.date :dtp_dose5
t.date :tdap_dose1
t.date :hpv_dose1
t.date :hpv_dose2
t.date :hpv_dose3
end
end
def down
# Drop vaccination_schedules table
drop_table :vaccination_schedules
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
models/vaccination_schedule.rb
|
#Model for Vaccination Schedule table:
class VaccinationSchedule < ActiveRecord::Base
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/strings.rb
|
class MessengerBot
GREETING_MESSAGE_SALUTATION = {
"en" => "Hey ",
"ta" => "வணக்கம் "
}
GREETING_MESSAGE_CONTENT = {
"en" => "Glad to have you on board. I will keep reminding you about the vaccination days for your kids.",
"ta" => "விக்கிப்பீடியா உங்களை வரவேற்கிறது"
}
OLD_USER_GREETING_CONTENT = {
"en" => "You can edit your previous records, or continue with the same",
"ta" => "நீங்கள் முந்தைய பதிவுகளை திருத்தலாம், அல்லது அதே பதிவுடன் தொடரலாம்"
}
HI_MESSAGE_CONTENT = {
"en" => " Glad to see you!",
"ta" => "உங்களைப் பார்ப்பது மகிழ்ச்சி!"
}
UPCOMING_VACCINATION_DETAILS_BUTTON = {
"en" => "Upcoming Vaccination Details",
"ta" => "எதிர்வரும் தடுப்பூசி நாட்கள்"
}
PREVIOUS_VACCINATION_DETAILS_BUTTON = {
"en" => "Previous Vaccination Details",
"ta" => "முந்தைய தடுப்பூசி நாட்கள்"
}
SUBSCRIPTION_BUTTON = {
"en" => "Subscription",
"ta" => "சந்தா"
}
PROFILE_BUTTON = {
"en" => "Profile",
"ta" => "சுயவிவரம்"
}
MORE_BUTTON = {
"en" => "More",
"ta" => "மேலும்"
}
DETAILS_BUTTON = {
"en" => "Details",
"ta" => "விவரங்கள்"
}
DUE_DATE ={
"en" => "Due date",
"ta" => "தேதி"
}
HELP_TEXT = {
"en" => "Try these simple commands,\n*Show my upcoming vaccines\n*what are my past vaccines?\n*change my kid name\n*show my profile",
"ta" => "இந்த எளிய கட்டளைகளை முயற்சிக்கவும் \n * என் வரவிருக்கும் தடுப்பூசிகளை காட்டுக \n * எனது கடந்த தடுப்பூசிகள் என்ன? \n * என் குழந்தையின் பெயரை மாற்றவும் \n * என் சுயவிவரத்தைக் காட்டு"
}
UPCOMING_VACCINATION_MESSAGE_TEXT = {
"en" => "upcoming vaccines",
"ta" => "எதிர்வரும் தடுப்பூசி"
}
PREVIOUS_VACCINATION_MESSAGE_TEXT = {
"en" => "previous vaccines",
"ta" => "முந்தைய தடுப்பூசிகள்"
}
PROFILE_MESSAGE_TEXT = {
"en" => "profile",
"ta" => "சுயவிவரம்"
}
EDIT_KID_NAME_TEXT = {
"en" => "edit kid name",
"ta" => "குழந்தை பெயரை திருத்தவும்"
}
EDIT_KID_DOB_TEXT = {
"en" => "edit kid dob",
"ta" => "குழந்தையின் பிறந்த தேதி திருத்தவும்"
}
EDIT_KID_GENDER_TEXT = {
"en" => "edit kid gender",
"ta" => "குழந்தை பாலினத்தை திருத்தவும்"
}
QUICK_REPLY_HEADER = {
"en" => "How can I help you?",
"ta" => "நான் உங்களுக்கு ஏவ்வாறு உதவ வேண்டும் "
}
QUICK_REPLIES_OPTIONS = {
"Upcoming Vaccines" => {
"en" => "Upcoming Vaccines",
"ta" => "எதிர்வரும் தடுப்பூசிகள்"
},
"Previous Vaccines" => {
"en" => "Previous Vaccines",
"ta" => "முந்தைய தடுப்பூசிகள்"
}
}
KID_GENDER_UPDATED_TEXT = {
"en" => "Done, We have edited your Kid Gender!",
"ta" => "முடிந்தது, நாங்கள் உங்கள் குழந்தை பாலினத்தை திருத்திவிட்டோம்!"
}
KID_DOB_UPDATED_TEXT = {
"en" => "Done, We have updated your Kid Date Of Birth!",
"ta" => "முடிந்தது, நாங்கள் உங்கள் பிறந்தநாள் பிறந்த நாளை திருத்திவிட்டோம்!"
}
KID_NAME_UPDATED_TEXT = {
"en" => "Done, We have updated your Kid Name as ",
"ta" => "முடிந்தது, உங்கள் குழந்தை பெயரை ஆக நாங்கள் திருத்திவிட்டோம்!"
}
ASK_DOB_TEXT = {
"en" => "What is your kid's DOB?",
"ta" => "உங்கள் குழந்தையின் பிறந்தநாள் என்ன?"
}
ASK_KID_NAME = {
"en" => "Tell me your your kid name",
"ta" => "உங்கள் குழந்தையின் பெயரை சொல்லவும்"
}
ASK_KID_GENDER = {
"en" => "Boy or Girl?",
"ta" => "ஆண் அல்லது பெண்?"
}
BOY_TEXT = {
"en" => "boy",
"ta" => "சிறுவன்"
}
MALE_TEXT = {
"en" => "male",
"ta" => "ஆண்"
}
GIRL_TEXT = {
"en" => "girl",
"ta" => "சிறுமி"
}
FEMALE_TEXT = {
"en" => "female",
"ta" => "பெண்"
}
GOT_IT_TEXT = {
"en" => "Got it, ",
"ta" => "புரிந்தது"
}
INVALID_DOB_ERROR_TEXT = {
"en" => "Invalid Date , provide it in DD-MM-YYYY format",
"ta" => "தவறான தேதி, DD-MM-YYYY வடிவத்தில் வழங்கவும்"
}
INVALID_GENDER_ERROR_TEXT = {
"en" => "Please provide a valid gender!",
"ta" => "சரியான பாலினத்தை வழங்கவும்!"
}
REGISTERATION_SUCCESSFULL_TEXT = {
"en" => "Thanks for registering your kid details. We will notify you before the vaccination days.",
"ta" => "உங்கள் குழந்தை விவரங்களை பதிவு செய்வதற்கு நன்றி. தடுப்பூசி நாட்களுக்கு முன்னர் நாங்கள் உங்களுக்கு அறிவிப்போம்."
}
YOUR_NAME = {
"en" => "Your Name",
"ta" => "உங்கள் பெயர்"
}
YOUR_KID_NAME = {
"en" => "Kid Name",
"ta" => "குழந்தை பெயர்"
}
KID_DOB = {
"en" => "Date Of Birth",
"ta" => "பிறந்த நாள்"
}
KID_GENDER = {
"en" => "Kid Gender",
"ta" => "குழந்தை பாலினம்"
}
WHY_SUBSCRIBE_TEXT = {
"en" => "I will remind you about the vaccination days for your kid on the appropriate dates.",
"ta" => "உங்களின் குழந்தைக்கு பொருத்தமான தேதிகளில் தடுப்பூசி நாட்கள் பற்றி நான் நினைவூட்டுவேன்."
}
COULDNOT_UNDERSTAND_THE_MESSAGE_TEXT = {
"en" => "Sorry I couldn't understand that.. 🙁",
"ta" => "மன்னிக்கவும் எனக்கு புரியவில்லை .. 🙁"
}
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
wit/get_wit_message.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
require 'wit'
class Wit
#Method to get entities from wit server
def get_intent(word)
client = Wit.new(access_token: ENV["WIT_ACCESS_TOKEN"])
response = client.message(word)
if response["entities"]["intent"] != nil then
if response["entities"].length >1 then
return response["entities"]
else
return response["entities"]["intent"][0]["value"]
end
elsif response["entities"]["greetings"] != nil then
return "HI"
elsif response["entities"]["vaccine"] != nil then
return response["entities"]
else
return "NOTHING"
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
database_editors/vaccination_schedule_editor.rb
|
<gh_stars>1-10
require 'date'
require 'sinatra/activerecord'
require './models/default_vaccine_schedule'
require './models/vaccination_schedule'
require_relative '../facebookBot/bot'
require_relative '../utils'
class VaccinationScheduleEditor
VACCINE_COLUMNS_INDEX_STARTS_AT = 10
#Method to get user Facebook profile details
def get_profile(id)
fb_profile_url = FB_PROFILE + id + FB_PROFILE_FIELDS
profile_details = HTTParty.get(fb_profile_url)
@first_name = profile_details["first_name"]
@last_name = profile_details["last_name"]
@profile_pic = profile_details["profile_pic"]
@locale = profile_details["locale"]
@gender = profile_details["gender"]
end
#Method to fill details of kid
def add_new_kid(id,kid_name,kid_gender,kid_dob)
#To get the details from facebook
get_profile(id)
@language = @locale[0,2]
#create database instance
user = VaccinationSchedule.find_by_parent_facebook_userid(id)
if (user == nil) then
t = VaccinationSchedule.new
# update table columns with facebook profile details
t.parent_facebook_userid =id
t.parent_first_name =@first_name
t.parent_last_name =@last_name
t.parent_gender =@gender
t.locale =@locale
t.subscription =true
# fill the kid's details
t.kid_name = kid_name
t.kid_gender = kid_gender
t.kid_dob = kid_dob
t.save
# fill the vaccination dates in database
VaccinationScheduleEditor.new.update_kid_record(id,kid_dob)
else
MessengerBot.say(id,ALREADY_SUBSCRIBED_TEXT["#{@language}"])
end
end
#Method to update kid vaccination date records
def update_kid_record(id,kid_dob)
kid_record = VaccinationSchedule.find_by_parent_facebook_userid(id)
if kid_record != nil then
columns = VaccinationSchedule.column_names
for i in VACCINE_COLUMNS_INDEX_STARTS_AT..columns.length-1
d = DefaultVaccineSchedule.find_by_vaccine_name("#{columns[i]}")
kid_record.update_attributes("#{columns[i]}" => kid_dob + d.due_date)
end
else
MessengerBot.say(id,NOT_REGISTER_TEXT["#{@language}"])
end
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
db/schema.rb
|
<filename>db/schema.rb
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20180124144830) do
create_table "default_vaccine_schedules", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "vaccine_name"
t.integer "due_date"
t.string "url"
end
create_table "vaccination_schedules", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.string "parent_facebook_userid"
t.string "parent_first_name"
t.string "parent_last_name"
t.string "parent_gender"
t.string "locale"
t.boolean "subscription"
t.string "kid_name"
t.date "kid_dob"
t.string "kid_gender"
t.date "bcg_dose1"
t.date "hepb_dose1"
t.date "poliovirus_dose1"
t.date "hepb_dose2"
t.date "poliovirus_dose2"
t.date "dtp_dose1"
t.date "hib_dose1"
t.date "pcv_dose1"
t.date "rv_dose1"
t.date "poliovirus_dose3"
t.date "dtp_dose2"
t.date "hib_dose2"
t.date "pcv_dose2"
t.date "rv_dose2"
t.date "hepb_dose3"
t.date "dtp_dose3"
t.date "hib_dose3"
t.date "pcv_dose3"
t.date "rv_dose3"
t.date "typhoid_dose1"
t.date "mmr_dose1"
t.date "dtp_dose4"
t.date "hib_dose4"
t.date "pcv_dose4"
t.date "varicella_dose1"
t.date "hepa_dose1"
t.date "mmr_dose2"
t.date "varicella_dose2"
t.date "hepa_dose2"
t.date "typhoid_dose2"
t.date "dtp_dose5"
t.date "tdap_dose1"
t.date "hpv_dose1"
t.date "hpv_dose2"
t.date "hpv_dose3"
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
database_editors/db_strings.rb
|
<gh_stars>1-10
LIST_OF_UPCOMING_VACCINES_TEXT = {
"en" => "Here are the list of upcoming vaccines for your kid",
"ta" => "உங்கள் பிள்ளையின் எதிர்வரும் தடுப்பூசிகளின் பட்டியல் இங்கே"
}
LIST_OF_PROVIDED_VACCINES_TEXT = {
"en" => "Here are the list of provided vaccines for your kid",
"ta" => "உங்கள் குழந்தைக்கு வழங்கப்பட்ட தடுப்பூசிகளின் பட்டியல் இங்கே"
}
ALL_VACCINES_PROVIDED_MESSAGE_TEXT = {
"en" => "Congrats you have successfully provided all the vaccines to your kid!",
"ta" => "உங்கள் குழந்தைக்கு வெற்றிகரமாக எல்லா தடுப்பூசிகளையும் வெற்றிகரமாக வழங்கியுள்ளீர்கள்!"
}
REGISTERED_WITH_FUTURE_DATE_TEXT = {
"en" => "You have registered with future date as your kid date of birth! Please check and edit it.",
"ta" => "குழந்தை பிறந்த நாளன்று நீங்கள் எதிர்கால தேதியில் பதிவு செய்துள்ளீர்கள்! சரிபார்த்து அதை திருத்தவும். "
}
ASK_TO_REGISTER_TEXT = {
"en" => "Please Register your details first!",
"ta" => "முதலில் உங்கள் விவரங்களை பதிவு செய்யுங்கள்!"
}
NO_VACCINE_FOUND_TEXT = {
"en" => "Sorry, there is no vaccine under the name",
"ta" => "மன்னிக்கவும், பெயரில் தடுப்பூசி இல்லை"
}
CHECK_OUT_SPELLING_TEXT = {
"en" => " please check your spelling!",
"ta" => "உங்கள் உச்சரிப்பு சரிபார்க்கவும்!"
}
ALREADY_SUBSCRIBED_TEXT = {
"en" => "You are already subscribed!",
"ta" => "நீங்கள் ஏற்கனவே சந்தா செலுத்திவிட்டீர்கள்!"
}
NOT_REGISTER_TEXT = {
"en" => "You are not registered user!",
"ta" => "நீங்கள் பதிவு செய்த பயனர் இல்லை!"
}
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
config.ru
|
require './app'
require 'facebook/messenger'
require_relative 'facebookBot/bot'
require 'rake'
# you may need this lines in order to test your server before you create bot.rb later
# run regular sinatra for other paths (in case you ever need it)
run Sinatra::Application
# run both Sinatra and facebook-messenger on /webhook
map("/webhook") do
run Facebook::Messenger::Server
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
subscription/subscription_strings.rb
|
<filename>subscription/subscription_strings.rb
SHOW_SUBSCRIBE_SUBTITLE_TEXT = {
"en" => "You are now Unsubscribed to Vaccine reminder. Do you want to Subscribe?",
"ta" => "நீங்கள் இப்போது தடுப்பூசி நினைவூட்டலுக்கு குழு சேரவில்லை . நீங்கள் குழுசேர விரும்புகிறீர்களா?"
}
SHOW_UNSUBSCRIBE_SUBTITLE_TEXT = {
"en" => "You are now subscribed to Vaccine reminder. Do you want to Unsubscribe?",
"ta" => "நீங்கள் இப்போது தடுப்பூசி நினைவூட்டலுக்கு குழுசேர்ந்துள்ளீர்கள். நீங்கள் குழுவிலக வேண்டுமா?"
}
SUBSCRIPTION_TEXT = {
"en" => "Subscription",
"ta" => "சந்தா"
}
UNSUBSCRIBE_BUTTON = {
"en" => "Unsubscribe",
"ta" => "குழுவிலகல்"
}
SUBSCRIBE_BUTTON = {
"en" => "Subscribe",
"ta" => "பதிவு"
}
WHY_SUBSCRIBE_BUTTON = {
"en" => "Why Subscribe",
"ta" => "ஏன் பதிவு செய்கிறீர்கள்"
}
SUCCESSFULLY_SUBSCRIBED_TEXT1 = {
"en" => "You are successfully Subscribed!!",
"ta" => "நீங்கள் வெற்றிகரமாக குழுசேர்ந்துள்ளீர்கள்!"
}
SUCCESSFULLY_SUBSCRIBED_TEXT2 ={
"en" => "Thank you for subscribing, I'll send you Vaccine reminders regularly !",
"ta" => "சந்தாவிற்கு நன்றி, நான் வழக்கமாக தடுப்பூசி நினைவூட்டல்களை அனுப்புவேன்!"
}
SUCCESSFULLY_UNSUBSCRIBED_TEXT ={
"en" => "You are successfully Unsubscribed! To get regular vaccine reminders, do subscribe!",
"ta" => "நீங்கள் வெற்றிகரமாக குழுவிலக்கப்பட்டுள்ளீர்கள்! வழக்கமான தடுப்பூசி நினைவூட்டல்களைப் பெற, பதிவு செய்க!"
}
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
database_editors/default_vaccine_schedule_filler.rb
|
<filename>database_editors/default_vaccine_schedule_filler.rb
require 'sinatra/activerecord'
require './models/default_vaccine_schedule'
require './models/vaccination_schedule'
#Fill Default vaccination table
t = DefaultVaccineSchedule.new
t.vaccine_name = "bcg_dose1"
t.due_date =0
t.url ="https://en.wikipedia.org/wiki/BCG_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hepb_dose1"
t.due_date =0
t.url ="https://en.wikipedia.org/wiki/Hepatitis_B_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hepb_dose2"
t.due_date =28
t.url ="https://en.wikipedia.org/wiki/Hepatitis_B_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hepb_dose3"
t.due_date =28+56
t.url ="https://en.wikipedia.org/wiki/Hepatitis_B_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="poliovirus_dose1"
t.due_date =0
t.url ="https://en.wikipedia.org/wiki/Polio_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="poliovirus_dose2"
t.due_date =28
t.url ="https://en.wikipedia.org/wiki/Polio_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="poliovirus_dose3"
t.due_date =28+28
t.url ="https://en.wikipedia.org/wiki/Polio_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="dtp_dose1"
t.due_date =42
t.url ="https://en.wikipedia.org/wiki/DPT_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="dtp_dose2"
t.due_date =42+28
t.url ="https://en.wikipedia.org/wiki/DPT_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="dtp_dose3"
t.due_date =42+28+28
t.url ="https://en.wikipedia.org/wiki/DPT_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="dtp_dose4"
t.due_date =42+28+28+180
t.url ="https://en.wikipedia.org/wiki/DPT_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="dtp_dose5"
t.due_date =42+28+28+180+1095
t.url ="https://en.wikipedia.org/wiki/DPT_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hib_dose1"
t.due_date =42
t.url = "https://en.wikipedia.org/wiki/Hib_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hib_dose2"
t.due_date =42+28
t.url = "https://en.wikipedia.org/wiki/Hib_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hib_dose3"
t.due_date =42+28+28
t.url = "https://en.wikipedia.org/wiki/Hib_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hib_dose4"
t.due_date =42+28+28+180
t.url = "https://en.wikipedia.org/wiki/Hib_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="pcv_dose1"
t.due_date =42
t.url = "https://en.wikipedia.org/wiki/Pneumococcal_conjugate_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="pcv_dose2"
t.due_date =42+28
t.url = "https://en.wikipedia.org/wiki/Pneumococcal_conjugate_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="pcv_dose3"
t.due_date =42+28+28
t.url = "https://en.wikipedia.org/wiki/Pneumococcal_conjugate_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="pcv_dose4"
t.due_date =42+28+28+180
t.url = "https://en.wikipedia.org/wiki/Pneumococcal_conjugate_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="rv_dose1"
t.due_date =42
t.url = "https://en.wikipedia.org/wiki/Rotavirus_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="rv_dose2"
t.due_date =42+28
t.url = "https://en.wikipedia.org/wiki/Rotavirus_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="rv_dose3"
t.due_date =42+28+28
t.url = "https://en.wikipedia.org/wiki/Rotavirus_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="typhoid_dose1"
t.due_date =270
t.url = "https://en.wikipedia.org/wiki/Typhoid_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="typhoid_dose2"
t.due_date =270+450
t.url = "https://en.wikipedia.org/wiki/Typhoid_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="mmr_dose1"
t.due_date =270
t.url = "https://en.wikipedia.org/wiki/MMR_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="mmr_dose2"
t.due_date =270+180
t.url = "https://en.wikipedia.org/wiki/MMR_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="varicella_dose1"
t.due_date =365
t.url = "https://en.wikipedia.org/wiki/Varicella_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="varicella_dose2"
t.due_date =365+90
t.url = "https://en.wikipedia.org/wiki/Varicella_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hepa_dose1"
t.due_date =365
t.url = "https://en.wikipedia.org/wiki/Hepatitis_A_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hepa_dose2"
t.due_date =365+180
t.url = "https://en.wikipedia.org/wiki/Hepatitis_A_vaccine"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="tdap_dose1"
t.due_date =2555
t.url = "https://en.wikipedia.org/wiki/DPT_vaccine#Tdap"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hpv_dose1"
t.due_date =3285
t.url = "https://en.wikipedia.org/wiki/HPV_vaccines"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hpv_dose2"
t.due_date =5475
t.url = "https://en.wikipedia.org/wiki/HPV_vaccines"
t.save
t = DefaultVaccineSchedule.new
t.vaccine_name ="hpv_dose3"
t.due_date =5475
t.url = "https://en.wikipedia.org/wiki/HPV_vaccines"
t.save
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
models/default_vaccine_schedule.rb
|
#The Model for a table that holds the default values for Vaccine reminder
class DefaultVaccineSchedule < ActiveRecord::Base
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
db/migrate/20180124144830_create_default_vaccine_schedule.rb
|
<reponame>Balaji-Ramasubramanian/Smart-Vaccine-Remainder
#Database table to store the default values for vaccine table
class CreateDefaultVaccineSchedule < ActiveRecord::Migration[5.1]
def up
create_table :default_vaccine_schedules do |t|
t.string :vaccine_name
t.integer :due_date
t.string :url
end
end
def down
# Drop default_vaccine_schedule table
drop_table :default_vaccine_schedules
end
end
|
Balaji-Ramasubramanian/Smart-Vaccine-Remainder
|
facebookBot/json_templates/greeting.rb
|
class MessengerBot
GREETING = {
"greeting": [{
"locale": "default",
"text": "Hey {{user_full_name}}, Welcome to Smart Vaccine reminder Bot. \nWe are here to help you on reminding the vaccination days for your kids."
}]
}
end
|
willrax/motion-giphy
|
lib/motion-giphy/pagination.rb
|
class MotionGiphy
module Pagination
attr_reader :total, :count, :offset
def initialize(pagination)
@total = pagination["total_count"]
@count = pagination["count"]
@offset = pagination["offset"]
end
end
end
|
willrax/motion-giphy
|
lib/motion-giphy/meta.rb
|
module MotionGiphy
class Meta
attr_reader :message, :status
def initialize(meta)
@message = meta["message"]
@status = meta["status"]
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.