text stringlengths 10 2.61M |
|---|
#this example demonstrates the use of 2d array in ruby
#declaration of a 2d array
cells = [
[1,2,3,4,5],
[6,7,8,9,10],
['a','b',4,'f','c','k']
]
#now print the array in traditional format
cells.each do |row| #iterate over each row
row.each do |col| #iterate over each column
print "#{col}"... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
unless ENV['NODES'].nil? || ENV['NODES'] == 0
count = ENV['NODES'].to_i
else
count = 5
end
Vagrant.configure("2") do |config|
config.vm.box = "generic/ubuntu2004"
config.vm.network "private_network", type: "dhcp"
config.ssh.insert_key = false
config.vm.provider :l... |
# encoding: UTF-8
require 'test/unit'
require 'test_helper'
class TextLibXslt < Test::Unit::TestCase
def test_constants
assert_instance_of(Fixnum, XSLT::MAX_DEPTH)
assert_instance_of(Fixnum, XSLT::MAX_SORT)
assert_instance_of(String, XSLT::ENGINE_VERSION)
assert_instance_of(Fixnum, XSLT::LIBXSLT_VERS... |
module EasyMapper
module Adapters
module Results
class PostgreResult
def initialize(result)
@result = result
end
def single_hash
list.first
end
def single_value
@result.values.first.first
end
def values
@resul... |
module PublicRescue
module Generators
class PublicRescueGenerator < Rails::Generators::Base
namespace 'public_rescue'
source_root File.expand_path("../../../../", __FILE__)
desc "Creates a controller that inherits from PublicRescue::PublicErrorsController."
def create_controller_fi... |
$:.unshift './lib'
require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
# require 'mina/rbenv' # for rbenv support. (http://rbenv.org)
require 'mina/rvm' # for rvm support. (http://rvm.io)
require 'mina/defaults'
require 'mina/extras'
require 'mina/god'
require 'mina/unicorn'
require 'mina/nginx'
require... |
FactoryGirl.define do
factory :user do
sequence(:email) { |n| "email#{n}@example.com" }
password 'password'
first_name 'First'
last_name 'Last'
is_admin false
trait :admin do
is_admin true
end
end
factory :presentation do
sequence(:title) { |n| "Presentation #{n}" }
da... |
class OpenMic
attr_accessor :location,
:date,
:performers
def initialize(location: "", date: "")
@location = location
@date = date
@performers = []
end
def welcome(names = [])
@performers << names
end
def repeated_jokes?
if @user.jokes.uniq.length == j... |
# encoding: utf-8
control "V-59855" do
title "Owners of privileged accounts must use non-privileged accounts for non-administrative activities."
desc "Use of privileged accounts for non-administrative purposes puts data at risk of unintended or unauthorized loss, modification, or exposure. In particular, DBA account... |
module Stinger
module Sharded
class Vulnerability < Sharded::Base
belongs_to :asset,
:class_name => 'Stinger::Sharded::Asset'
# belongs_to :cve won't work,
# as the Cve record is in a
# different DB
def cve
Stinger::Cve.find(cve_id)
end
end
end
e... |
require File.dirname(__FILE__) + '/../test_helper'
require 'text_pages_controller'
# Re-raise errors caught by the controller.
class TextPagesController; def rescue_action(e) raise e end; end
class TextPagesControllerTest < Test::Unit::TestCase
fixtures :text_pages
def setup
@controller = TextPagesController... |
require File.dirname(__FILE__) + '/../../test_helper'
class PrepTest < ActiveSupport::TestCase
context '#generate_product_json' do
def setup
@pp = Factory :partner_product
end
test 'should return nil if not send a partner product' do
assert_nil Publish::Prep.generate_product_jso... |
# frozen_string_literal: true
module ReactOnRails
VERSION = "2.3.0".freeze
end
|
require 'spec_helper'
describe "authentication feature", type: :feature do
describe "sign in" do
let(:user) { build(:user) }
let!(:account) { create(:account_with_schema, owner: user) }
it "should allow user sign in" do
sign_user_in(user, subdomain: account.subdomain)
response_body = JSON.p... |
module PrawnCharts
module Helpers
module Marker
# Given a marker number, min, max, and distance, interpolates even values across the distance.
#
# @param [Fixnum] markers Number of interpolations to make
# @param [Fixnum/Float] min Starting value
# @param [Fixnum/Float] max Ending v... |
class UsersController < ApplicationController
before_action :require_user_logged_in, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :set_user, only: [:edit, :update, :destroy]
def index
@users = User.alive_records.order(id: :asc).page(pa... |
class Comment < ActiveRecord::Base
attr_accessible :content, :parent_id, :post_id, :user_id
has_many :comment_attachments
belongs_to :post
def as_json(options={})
{
id: self.id,
parent_id: self.parent_id,
content: self.content,
comment_replies: self.child_comments_nested
... |
# frozen_string_literal: true
class FollowingController < ApplicationController
def index
user = User.find(params[:id])
following_ids = user.active_relationships.map { |a| a.followee_id }
@users = Kaminari.paginate_array(following_ids.map { |id| User.find(id) }).page(params[:page]).per(5)
end
end
|
# frozen_string_literal: true
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
desc 'Lint the application (Ruby/Coffeescript/Sass)'
task lint: %w(lin... |
#encoding: utf-8
class ApplicationController < ActionController::Base
include Pundit
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
around_filter :set_timezone
before_action :configure_devise_permitted_parameter... |
class BeerSong
def number_of_bottles(num)
if num > 1
"#{num} bottles"
elsif num == 1
"1 bottle"
elsif num == 0
"no more bottles"
end
end
def verse(num)
if num == 0
"No more bottles of beer on the wall, no more bottles of beer.\n" \
"Go to the store and buy some m... |
require_relative '../model/model'
class PrintScreen
def initialize
end
def menu
puts"Welcome to the Gumball Machine!\n
What would you like to do?\n
1. Check how many Gumballs\n
2. Remove Gumballs\n
3. Top Up machine\n
4. Exit"
return gets.... |
#!/usr/bin/env ruby
"""
Converts the IP ranges from their CIDR format into something that can be input
into an OpenVPN config.
"""
require 'ipaddr'
class IPAddr # From 'ipaddr' in stdlib
"""Add some nicer methods to return the IP / subnet."""
def get_ip
self.inspect.split(/[\/:]/).slice(2)
end
def get_s... |
class Event < ApplicationRecord
belongs_to :laboratory
belongs_to :member
DEFAULT_START_DAY = Date.current+1.day+8.hour
DEFAULT_FINISH_DAY = Date.current+1.day+20.hour
validates :started_at , presence: true
validates :finished_at , presence: true
validates :status , presence: true
validates ... |
require 'rails_helper'
describe "Create a team", type: :feature, js: true do
context "when team name is invalid" do
it "shows an error message" do
team_name = "Team invalid name"
create_team_flow(team_name)
expect(page).to have_css("#toast-container", visible: :all)
expect(page).to have... |
class AddLatitudesToSpot < ActiveRecord::Migration
def change
add_column :spots, :state, :string
add_column :spots, :latitude, :string
add_column :spots, :longitude, :string
add_column :spots, :gmaps, :boolean
end
end
|
# encoding: utf-8
require 'pedlar'
class PathstringInterface < String
# delegations
extend Pedlar
# what we shamelessly steal from Pathname
def_delegator :@absolute, :to_s, :absolute
def_delegator :@absolute, :dirname, :absolute_dirname
# here with a failsafe thanks to Pedlar
safe_delegator :@relati... |
require 'yt/collections/playlists'
module Yt
module Collections
class RelatedPlaylists < Playlists
private
# Retrieving related playlists requires to hit the /channels endpoint.
def list_resources
'channels'
end
# The related playlists are included in the content details of... |
class ReportsController < ApplicationController
add_breadcrumb I18n.t('breadcrumbs.home'), :root_path,
:only => [:index, :show]
add_breadcrumb I18n.t('breadcrumbs.report'), :reports_path,
:only => [:index, :show]
require 'spreadsheet'
require 'matrix'
require 'rserve'
include Rserve
def index
... |
class StatusEntry < ActiveRecord::Base
has_one :feed_update, as: :entry
validates :body, presence: true
end
|
class Admin::ReviewActivity < ActiveRecord::Base
belongs_to :review_project
has_many :person_activity_relations, :class_name => 'Admin::PersonActivityRelation', :foreign_key => :activity_id
has_many :pre_activity_relations, :class_name => 'Admin::ReviewActivityRelation', :foreign_key => :activity_id
#提供系统一个时间判断... |
class AddHoraToEventoEscuela < ActiveRecord::Migration[5.1]
def change
add_column :evento_escuelas, :hora, :string
end
end
|
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# exam_id :integer
# name :text(255)
# value :integer
# created_at :datetime
# updated_at :datetime
# form :int... |
module Events
module Subscriber
def self.included(base)
base.send :include, EventNaming
base.extend ClassMethods
end
def handles?(event_name)
handler_name = create_handler_name(event_name)
self.respond_to?(handler_name)
end
module ClassMethods
def handle(event_name,... |
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def date_view(time)
date = time.to_date
view = Date::DAYNAMES[date.cwday]
view += ' <b style="font-size: 120%;">' << print_number(date.month) << '-' << print_number(date.mday) << '</b> ' <<
prin... |
json.array!(@appointments) do |appointment|
json.extract! appointment, :id, :name, :kind, :date, :location, :contact,
json.url appointment_url(appointment, format: :json)
end
z |
#Make constant
module Constants
EMPLOYMENT_TYPE = {
'': 0,
'Bán thời gian': 1,
'Toàn thời gian': 2,
'Thời vụ': 3,
'Khác': 99
}
OCUPATION = {
'': 0,
'Sinh viên': 1,
'Học sinh': 2,
'Nội trợ': 3,
'Làm việc tự do': 4,
'Đang đi làm': 5,
'Khác': 99
}
REGISTER_COMPA... |
class Author < ApplicationRecord
validates_presence_of :name
validates_uniqueness_of :name
has_many :books
end
|
require 'spec_helper'
RSpec.describe BoatsController do
let!(:manufacturer) { create :manufacturer }
let!(:model) { create :model, manufacturer: manufacturer }
let!(:currency) { create :currency }
let!(:boat_without_country) { create :boat, country: nil, model: model, manufacturer: manufacturer, currency: curr... |
class GradeEnrollment < ApplicationRecord
belongs_to :student
belongs_to :grade
end
|
class User < ApplicationRecord
attr_accessor :remember_token
before_save { self.email = email.downcase }
before_save :build_invitation_code
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum:... |
require 'falcon/version'
module Git
def show_build_tags
system "git for-each-ref --format='%(refname:short)' --sort=-taggerdate refs/tags | grep app_build_"
end
def add_build_tag
current_sha = %x[git rev-parse --short HEAD]
current_sha.strip!
system "git tag -a 'app_build_#{current_sha}' -m... |
FactoryBot.define do
factory :bundle do
name { FactoryBot.generate(:name) }
key { ::SecureRandom::hex(15) }
end
end
|
require "active_fedora/registered_attributes/version"
require 'active_attr'
require "active_fedora/registered_attributes/attribute"
require "active_fedora/registered_attributes/attribute_registry"
module ActiveFedora
module RegisteredAttributes
extend ActiveSupport::Concern
delegate :attribute_defaults, to:... |
Miletracker::Application.routes.draw do
devise_for :users,
:controllers => { :omniauth_callbacks => 'users/omniauth_callbacks' }
namespace :api do
api_version(module: 'v1', header: {name: 'API-VERSION', value: 'v1'},
parameter: {name: 'version', value: 'v1'},
path: {value:... |
# Time to restructure the code for Hard Mode so that it
# is in class Game
# Should set the number to be guessed in initialize
# Must Evaluate the quality of the user's guess to see
# if it helps them. To do this I will track their previous guess
# and I will compare the new guess with respect to the
# higher or lower... |
class AddProfitToRequest < ActiveRecord::Migration
def self.up
change_table :requests do |t|
t.float :profit, :null=>false, :default=>0.00
end
end
def self.down
remove_column :requests, :profit
end
end
|
require 'spec_helper'
describe HappyNumbers do
let(:test_cases) do
[
{
input: 1,
expect: 1
},
{
input: 7,
expect: 1
},
{
input: 22,
expect: 0
}
]
end
it 'returns 1 if happy numbers 0 if not' do
test_cases.each do |ro... |
# frozen_string_literal: true
require "abstract_unit"
require "active_support/cache"
class CacheStoreWriteMultiEntriesStoreProviderInterfaceTest < ActiveSupport::TestCase
setup do
@cache = ActiveSupport::Cache.lookup_store(:null_store)
end
test "fetch_multi uses write_multi_entries store provider interface... |
# Public: Multiplies an input Integer with itself.
#
# num - The Integer that will be squared.
#
# Examples
#
# square(6)
# # => 36
#
# Returns the input squared.
def square(num)
return num * num
end |
FactoryBot.define do
factory :answer do
user
question
body "MyText first"
end
factory :another_answer, class: "Answer" do
user
question
body "MyText another"
end
factory :invalid_answer, class: "Answer" do
user
question
body nil
end
end
|
class AddDirectorToDetails < ActiveRecord::Migration[5.0]
def change
add_column :details, :employee_name, :string
add_column :details, :title, :string
end
end
|
# frozen_string_literal: true
module Quilt
class Engine < ::Rails::Engine
isolate_namespace Quilt
config.quilt = Quilt.configuration
initializer(:initialize_quilt_logger, after: :initialize_logger) do
config.quilt.logger = ::Rails.logger
end
initializer(:mount_quilt, before: :add_builtin... |
class Listing < ActiveRecord::Base
def self.parse_address(raw_address)
address_words = raw_address.split(" ")
if address_words.last.include?("#") || address_words.last.downcase.include?("floor")
address_words[0...-1].join(" ")
else
raw_address.strip
end
end
def self.parse_unit(raw_a... |
class DrinksController < ApplicationController
include CompanySupport
skip_before_filter :load_company, :only => [:making, :wants, :edit_with_token]
skip_before_filter :load_token, :only => [:making, :wants, :edit_with_token]
before_filter :must_edit, :except => [:making, :wants, :edit_with_token]
before_fi... |
class AddIndexToCharacterStatus < ActiveRecord::Migration
def change
add_index(:characters, [:status, :id])
end
end
|
module Trustworthy
class Key
attr_reader :x, :y
def self.create(slope, intercept)
x = Trustworthy::Random.number
y = slope * x + intercept
new(x, y)
end
def self.create_from_string(str)
x, y = str.split(',').map { |n| BigDecimal.new(n) }
Trustworthy::Key.new(x, y)
e... |
class PublishingCompany < ActiveHash::Base
self.data = [
{ id: 0, name: '---' },
{ id: 1, name: '講談社' },
{ id: 2, name: '集英社' },
{ id: 3, name: 'KADOKAWA' },
{ id: 4, name: '小学館' },
{ id: 5, name: 'ゼンリン' },
{ id: 6, name: '日経BP' },
{ id: 7, name: '学研HD' },
{ id: 8, name: 'ベネッセHD... |
module Closeio
class Client
module Report
# OPTIONS [date_start, date_end, user_id]
def activity_report(organization_id, options = {})
get("report/activity/#{organization_id}/?", options)
end
# OPTIONS [date_start, date_end]
def lead_status_report(organization_id, options = ... |
#
# Cookbook Name:: adminscripts
# Recipe:: vmware_quiesce
#
# Copyright 2014, HiST AITeL
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... |
# frozen_string_literal: true
# Preview all emails at http://localhost:3000/rails/mailers/user_mailer
class UserMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/permission_confirmation
def permission_confirmation
user = User.last
UserMailer.permi... |
# work in progress. May be unstable!
# TO-DO
# show the two methods of using Turnstile--as a Sinatra middleware, or using
# cascades.
require 'sinatra/base'
require 'moneta'
require 'moneta/memory'
require "#{File.dirname(__FILE__)}/lib/turnstile_app"
module Turnstile
class App < Sinatra::Base
register S... |
require "minitest/autorun"
require "minitest/pride"
require './lib/card'
require './lib/deck'
require "./lib/player"
require "./lib/turn"
require "./lib/game"
class GameTest < Minitest::Test
def test_it_exists
standard_deck = [
card1 = Card.new(:heart, "Jack", 11),
card2 = Card.new(:heart, "10", 10),... |
namespace :custom do
desc '自訂的前置任務。'
task :pre_setup do
on roles(:all) do
# do something before going to published
end
end
desc '自訂的後置任務。'
task :post_setup do
on roles(:all) do
# do something after deploy finished
end
end
end
|
require 'fileutils'
module Rack
module Deploy
# Given a directory, it initializes it to be a rack-enabled ASP.NET application
class ASPNETApplication
APP_TYPES = [:rails, :sinatra]
FILES_TO_EMIT = ['web.config', 'config.ru']
IRONRUBY_BINARIES = %W(
IronRuby.dll
Iron... |
require 'rails_helper'
RSpec.describe "milestone_reports/show", type: :view do
before(:each) do
@milestone_report = assign(:milestone_report, MilestoneReport.create!(
:milestone_id => "",
:status_cd => "MyText"
))
end
it "renders attributes in <p>" do
render
expect(rendered).to match... |
require 'spec_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by the Rails when you ran the scaffold generator.
describe MriScansController do
def mock_mri_scan(stubs={})
@mock_mr... |
require "chef/search/query"
class NagiosDataBags
attr_accessor :bag_list
def initialize(bag_list=nil)
if bag_list == nil
if Chef::Config[:solo]
unless File.directory?(Chef::Config[:data_bag_path])
raise Chef::Exceptions::InvalidDataBagPath, "Data bag path '#{Chef::Config[:data_bag_path... |
=begin
Write a method that takes a string as an argument and returns a new string in which every uppercase letter is replaced by its lowercase version, and every lowercase letter by its uppercase version. All other characters should be unchanged.
You may not use String#swapcase; write your own version of this meth... |
require 'test_helper'
class UserCreationTest < ActionDispatch::IntegrationTest
def setup
@admin = users(:cthulhu)
log_in_as(@admin)
@good_params = { name: 'Cheryl',
email: 'kristall@figgis.agency',
password: 'tunt4e... |
#
# Cookbook Name:: amazontimesync
# Recipe:: amazontimesync
#
# Copyright 2017, arvato systems GmbH
#
# All rights reserved - Do Not Redistribute
#
platformfamily = node['platform_family']
# uninstall ntp package if exist
package 'ntp' do
action :remove
end
# install chrony package
package 'chrony' do
action :i... |
require 'pry'
require 'spec_helper'
module Spree
describe Shipment, :vcr do
let!(:shipment) { order.shipments.first }
let!(:order) do
create(:order_with_line_items, line_items_count: 1, ship_address: to) do |order|
order.variants.each { |v| v.update! weight: 10 }
end
end
let(:to)... |
def myst(a,b)
x=a
y=b
until x == y
if x>y
x = x-y
else
y = y-x
end
end
x
end
#
# Complete the 'isPossible' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER a
# 2. INTEGER b
... |
require "rails_helper"
RSpec.describe User, type: :model do
it "cannot store the same user twice" do
user1 = User.create(facebook_id: 3434, first_name: "Andy", timezone: 2)
user2 = User.create(facebook_id: 3434, first_name: "Andy", timezone: 2)
expect(user2).not_to be_valid
end
it "must have a nam... |
require 'steam/version'
require 'steam/client'
module Steam
extend SingleForwardable
def_delegators :client, :game_scheme, :configure, :owned_games, :apps, :match, :history,
:history_sequence, :leagues, :live_leagues, :profiles, :profile, :bans, :friends, :heroes
def self.client
@client ||= Cl... |
require 'spec_helper'
describe Oargun::ControlledVocabularies::Organization do
describe "validation" do
subject { described_class.new(subject_term) }
context 'when the Organization is in the vocabulary' do
let(:subject_term) { RDF::URI.new('http://id.loc.gov/vocabulary/organizations/mtjg') }
it ... |
require 'test/unit'
# def solution(s)
# return 0 if s == s.reverse
#
# b = 0
# e = s.length - 1
# op = 0
# limit = s.length / 2
#
# while b != limit
# op += (s[e].ord - s[b].ord).abs if s[b] != s[e]
# b += 1
# e -= 1
# end
#
# op
# end
# cba
# abc
def solution(s)
s = s.codepoints
r = ... |
# frozen_string_literal: true
module Migration
class SolrObjectList
attr_reader :objects, :object_class
def initialize(object_class)
@object_class = object_class
@objects = ActiveFedora::SolrService.query(filter, fl: 'id,depositor_tesim', rows: 100000).map(&:id)
end
def each_with_load
... |
class Users::SessionsController < Devise::SessionsController
# before_action :configure_sign_in_params, only: [:create]
# acts_as_token_authentication_handler_for User
respond_to :json
skip_before_action :require_no_authentication, :only => [:create ,:new]
def create
resource = User.find_for_database_authentication(:l... |
namespace :db do
desc "Populate regions."
task :populate_regions => :environment do
reset(Region)
Region.create(:name => "Bomi", :capital => "Tubmanburg", :country => "Liberia")
Region.create(:name => "Bong", :capital => "Gbarnga", :country => "Liberia")
Region.create(:name => "Gbarpolu", :capital ... |
class CitizenMailer < ApplicationMailer
def create_or_update(citizen)
@citizen = citizen
mail(to: @citizen.email, subject: 'Your informations of citizen was added or updated.')
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'skit/amqp/version'
Gem::Specification.new do |spec|
spec.name = 'skit-amqp'
spec.version = Skit::AMQP::VERSION
spec.authors = ['Tomas Brazys', 'Tomas Varaneckas']
spe... |
class Project < ActiveRecord::Base
belongs_to :team
has_many :events, dependent: :destroy
has_many :users, -> { uniq }, through: :team
has_many :allocations
validates :team_id, presence: true
validates :name, presence: true
def self.name_for(id)
Project.find_by(id:id).name
end
def total_hours_u... |
require "rails_helper"
RSpec.describe BsnlSmsStatusJob, type: :job do
describe "#perform" do
it "raises an error if a detailable with the message ID doesn't exist" do
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with("BSNL_IHCI_HEADER").and_return("ABCDEF")
allow(ENV)... |
class WordTagRelationShip < ActiveRecord::Base
belongs_to :dictionary, class_name: "Dictionary"
belongs_to :tag, class_name: "Tag"
end
|
class ClassroomsController < ApplicationController
before_filter :require_moderator
def index
@classrooms = Classroom.includes(:subject).order(:description)
end
def destroy
@classroom = Classroom.find(params[:id])
@classroom.destroy
redirect_to classrooms_url, notice: 'Classroom deleted'
en... |
FactoryGirl.define do
factory :page do
title "MyPage"
content "A big content"
end
end |
class Cobweb::CrawlJob
require "net/https"
require "uri"
require "redis"
@queue = :cobweb_crawl_job
## redis params used
#
# crawl-counter
# crawled
# queue-counter
# statistics[:average_response_time]
# statistics[:maximum_response_time]
# statistics[:minimum_response_time]
# statistics[:a... |
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "schema_qualified_tables"
gem.summary = %Q{Logical schema names for ActiveRecord models}
gem.description = %Q{An ActiveRecord mix-in that makes it easier to use AR in an application which contains models wh... |
# Write a method, `only_vowels?(str)`, that accepts a string as an arg.
# The method should return true if the string contains only vowels.
# The method should return false otherwise.
# define vowels
# iterate through string and find if vowels.include?(char)
# if it doesn't include vowel return false, other return tru... |
class Api::V1::ReviewsController < Api::V1::ApiController
before_filter :getuser, :only => [:index]
respond_to :json
skip_before_filter :verify_authenticity_token
def index
prepare_pagination('/reviews')
@reviews = @user.reviews
respond_with @reviews
end
def create
if params[:user_id]
... |
class CreateApplications < ActiveRecord::Migration
def self.up
create_table :applications do |t|
t.string :name
t.string :email
t.string :phone
t.boolean :been_on_tour
t.integer :how_many_tours
t.text :chautauqua_contributions
t.text :chautauqua_experiences
t.text :... |
class Validator
attr_accessor :attr_name, :option
def initialize(attr_name, option)
@attr_name = attr_name
@option = option
end
def valid?(obj)
raise NotImplementError, 'You should override this method in subclass'
end
end
|
class ContactInviterEmailWorker < BaseWorker
def self.category; :invite end
def self.metric; :contact_email end
def perform(user_id, email, options = {})
perform_with_tracking(user_id, email, options) do
user = User.find(user_id)
ContactInviter.new(user).add_by_email!(email, options)
true
... |
# infinite loop
loop { puts "This will keep looping until yu hit Ctrl + c"
}
loop do
puts "This is a infinite loop haha - Hit Ctrl + c to cancel!"
end |
# Documentation: https://docs.brew.sh/Formula-Cookbook
# https://rubydoc.brew.sh/Formula
# PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
class Ardupy < Formula
desc "👭 👭 ArduPy makes MicroPython and Arduino work together perfectly."
homepage ""
url "https://github.co... |
module CurriculumGenerator
module Generator
class CvItem < BasicGenerator
def initialize(param, data, lang)
super(param, data, lang)
end
def generate
value = get_value(param)
unless value.is_a?(Array)
value = Array[value]
end
value.collect do |... |
=begin
Author: Pradeep Macharla
The SauceBrowserFactory is used to initialize the capabilities object and http_client object that are eventually passed to the browser
instance
# This file is NOT needed if you are using saucelabs gem
=end
require_relative 'parsed_values'
module SauceLabs
class SauceBrowserFactory
... |
class Store::Manager::Policies::PaymentsController < ApplicationController
# GET /store/manager/policies/payments
# GET /store/manager/policies/payments.json
def index
@store_manager_policies_payments = Store::Manager::Policies::Payment.all
respond_to do |format|
format.html # index.html.erb
... |
require "halcyoninae/commander"
require "halcyoninae/arguments_parser"
require "halcyoninae/options_parser"
module Halcyoninae
class CLI
def initialize(registries:, argv: ARGV)
@registries = registries
@argv = argv
end
def run
Halcyoninae::Commander.new(
registries: registries,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.