text stringlengths 10 2.61M |
|---|
module GenericNotificationsRails
module Delivery
class Base
def deliver(message,device)
raise "Unknown delivery type"
end
end
end
end
|
module Lookup
extend ActiveSupport::Concern
included do
validates :code, length: { maximum: 32 }, uniqueness: { case_sensitive: false }, presence: true
validates :label, length: { maximum: 256 }, uniqueness: { case_sensitive: false },
presence: true
end
end
|
require 'mods_helper'
class Collection < ApplicationRecord
include MedusaAutoHtml
include Uuidable
include Breadcrumb
include CascadedEventable
include CascadedRedFlaggable
include ResourceTypeable
include EmailPersonAssociator
include Eventable
email_person_association(:contact)
belongs_to :repo... |
require 'test_helper'
class Sampling::ProgramQuestionTest < ActiveSupport::TestCase
test "program is required" do
question = build_valid_question :program => nil
assert !question.valid?
assert question.errors['program']
end
test "text of question is between 1 and 255 characters" do
q... |
class MovieList
def initialize(list)
@films = CSV.read(list, col_sep: '|').map{ |s| Movie.new(s)}
end
def longest
@films.sort_by(&:timing).reverse.first(5)
end
def directors
@films.group_by(&:director).map{|dir,films| [dir,films.count]}.to_h
end
def actors
... |
package "supervisor"
template "/etc/supervisor/conf.d/quickfire.conf" do
source "quickfire.supervisord.conf.erb"
variables(
:number_worker => 1,
:working_dir => "/vagrant/"
)
end
execute "supervisor restart" do
command "supervisorctl reload"
end |
require 'spec_helper'
describe IntegerFormatValidator do
let(:klass) do
Class.new do
include ActiveWarnings
attr_accessor :string1
warnings do
validates :string1, integer_format: true
end
def self.name; "TestClass" end
end
end
let(:instance) { klass.new }
subject ... |
module Rfm
# Error is the base for the error hierarchy representing errors returned by Filemaker.
#
# One could raise a FileMakerError by doing:
# raise Rfm::Error.getError(102)
#
# It also takes an optional argument to give a more discriptive error message:
# err = Rfm::Error.getError(102, 'add desc... |
class OsbDeploymentTrackersController < ApplicationController
# GET /osb_deployment_trackers
# GET /osb_deployment_trackers.json
def index
@osb_deployment_trackers = OsbDeploymentTracker.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @osb_deployment_tracker... |
ActiveRecord::Schema.define(version: 20160730055223) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "move_pokemons", id: false, force: :cascade do |t|
t.integer "pokemon_id"
t.integer "move_id"
end
create_table "moves", force... |
module Greeting
def Greeting.say_hello name
puts "hello #{name}"
end
def Greeting.make_soup
puts "let's make some soup !"
yield "cabbage" if block_given?
puts "Soup is ready!"
end
end |
class AddLatLngToEmployees < ActiveRecord::Migration
def change
add_column :employees, :lat, :decimal, {:precision=>10, :scale=>6, default: 0}
add_column :employees, :lng, :decimal, {:precision=>10, :scale=>6, default: 0}
end
end
|
module DatabasePlumber
class LeakFinder
class InvalidModelError < StandardError ; end
IGNORED_AR_INTERNALS = [ActiveRecord::SchemaMigration]
private_constant :IGNORED_AR_INTERNALS
def self.inspect(options = {})
new(options).inspect
end
def initialize(options)
@ignored_models = (... |
#!/usr/bin/env ruby
require 'pathname'
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', Pathname.new(__FILE__).realpath)
require 'rubygems'
require 'bundler/setup'
require 'find'
require 'hellgrid'
folders = ARGV.empty? ? [Dir.pwd] : ARGV
folders.each do |folder|
matrix = Hellgrid::Matrix.new
Find.... |
class ApiController < ApplicationController
skip_before_action :verify_authenticity_token
def info
if request_valid? then
@data[:date] = Date.parse(@data[:date])
@res = { :booked => false }
existing_booking = Booking.where('"end" > :date AND start <= :date AND room_id = :room', {
dat... |
class AddIndexOnPropertyid < ActiveRecord::Migration
def change
add_index :properties, :propertyid, unique: true
end
end
|
class ChatThread < ActiveRecord::Base
attr_accessible :user_id, :other_id, :messages_attributes
belongs_to :user
has_many :messages, inverse_of: :chat_thread
accepts_nested_attributes_for :messages
validates :user_id, :other_id, presence: true
def other_person
User.find(self.other_id)
end
end |
class City < ActiveRecord::Base
validates :name, presence: true
has_many :rentals
belongs_to :state
belongs_to :county
end
|
class CreateVisitActions < ActiveRecord::Migration
def change
create_table :visit_actions do |t|
t.integer :visit_id
t.integer :user_id
t.timestamp :server_time
t.string :url
t.string :referrer_url
t.string :page_title
t.string :page
t.string :entity
t.string ... |
require 'aws/templates/utils'
module Aws
module Templates
module Utils
module Parametrized
class Transformation
##
# Syntax sugar for transformations definition
#
# It injects the methods as class-scope methods into mixing classes.
# The methods are... |
require 'spec_helper'
describe Video do
# it "saves itself" do
# video = Video.new(name: "monk", description: "great video")
# video.save
# expect(Video.first).to eq(video)
# end
it {should belong_to(:category)}
it {should validate_presence_of(:name)}
it {should validate_presence_of(:description)}
it {sho... |
module Middleman
module Blog
# A sitemap plugin that adds tag pages to the sitemap
# based on the tags of blog articles.
class TagPages
def initialize(app)
@app = app
end
# Update the main sitemap resource list
# @return [void]
def manipulate_resource_list(res... |
module DynamicHelper
def field_title(obj, field)
field["name"]
end
def field_value(obj, field, empty: t('empty_value', scope: :dynamic_fields))
return empty if ((field["value"].nil?) or
(not field["value"].is_a? Numeric and field["value"].empty?)) and
(fiel... |
#!/run/current-system/sw/bin/vpsadmin-api-ruby
# Reconfigure shaper on selected nodes
#
# Usage: $0 <location domains> [execute]
#
require 'vpsadmin'
NEW_LIMIT = 1000*1024*1024 # bps
module TransactionChains
module Maintenance
remove_const(:Custom)
class Custom < TransactionChain
label 'Shaper'
... |
module Net
RSpec.describe ICAPResponse do
SUCCESS_STATUS = "ICAP/1.0 200 OK"
it "reads code from status line" do
io = StringIO.new SUCCESS_STATUS
code, _ = ICAPResponse.send(:read_status_line, io)
expect(code).to eq '200'
end
it "reads message from status line" do
io = StringI... |
require 'spec_helper'
describe "profiles/show" do
fixtures :all
before(:each) do
@profile = assign(:profile, profiles(:admin))
view.stub(:current_user).and_return(User.find_by(username: 'enjuadmin'))
end
describe "when logged in as Librarian" do
before(:each) do
@profile = assign(:profile, ... |
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
%w(fileutils set).each { |r| require r }
module DataMetaDom
=begin
Converter (ser/deser) code common to the DataMeta DOM.
For command line details either check the new method's sour... |
class UserMailer < ApplicationMailer
def welcome(user)
@user = user
mail to: @user.email, subject: "Welcome to Gearz! You are now registered. Start adding and renting
gear!", from: "Adam.@Gears.com"
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'lite_spec_helper'
require 'support/shared/protocol'
describe Mongo::Protocol::KillCursors do
let(:opcode) { 2007 }
let(:cursor_ids) { [123, 456, 789] }
let(:id_count) { cursor_ids.size }
let(:collection_name) { 'protocol-test' }
let(:database)... |
require 'spec_helper_acceptance'
require 'pry'
describe 'Solaris pkg_variant provider' do
# a manifest to add a variant
pp = <<-EOP
pkg_variant { 'variant.foo':
ensure => 'present',
value => 'bar',
}
EOP
context "when adding a variant" do
it 'should apply a manifest with no errors' ... |
# == Schema Information
#
# Table name: api_keys
#
# id :integer not null, primary key
# access_token :string
# created_at :datetime not null
# updated_at :datetime not null
# count :integer default(0), not null
#
class ApiKey < ActiveRecord::Base
before_cr... |
module Rongcloud
module Service
class Chatroom < Rongcloud::Service::Model
attr_accessor :chatroom_id
attr_accessor :user_id
attr_accessor :minute
attr_accessor :user_gag_list
def create
post = {uri: Rongcloud::Service::API_URI[:CHATROOM_CREATE],
params: opti... |
$script = <<-SCRIPT
apt-get update
apt-get install git docker docker-compose -y
apt-get install landscape-common -y
wget --quiet --no-check-certificate -O Dynatrace-OneAgent-Linux-latest.sh "https://syb31902.sprint.dynatracelabs.com/api/v1/deployment/installer/agent/unix/default/latest?Api-Token=APITOKEN&arch=x86&flavo... |
require 'spec_helper'
require "rails/all"
require 'rails_helper'
describe "Static pages" do
describe "Home page" do
it "have the content 'Sample App'" do
visit '/static_pages/home'
expect(page).to have_content('Sample App')
end
it "have the title 'Home'" do
visit '/static_pages/home'... |
# Copyright (c) 2006, 2007 Ruffdogs Software, Inc.
# Authors: Adam Lebsack <adam@holonyx.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.
#
# This program ... |
RSpec.feature "Users can view actuals in tab within a report" do
context "as a partner organisation user" do
let(:organisation) { create(:partner_organisation) }
let(:user) { create(:partner_organisation_user, organisation: organisation) }
before do
authenticate!(user: user)
end
after { lo... |
json.data do |json|
json.array!(@products) do |product|
json.extract! product, :id, :name, :price
json.url product_url(product, format: :json)
end
end
|
class ChangeAuditReportWegoauditId < ActiveRecord::Migration
def up
remove_column :audit_reports, :wegoaudit_id
add_column :audit_reports, :wegoaudit_id, :uuid, null: false
end
def down
remove_column :audit_reports, :wegoaudit_id
add_column :audit_reports, :wegoaudit_id, :integer
end
end
|
class Pokemon
attr_accessor :id, :name, :type, :db, :hp
def initialize(id:,name:,type:,db:,hp:nil)
@db = db
@name = name
@type = type
@id = id
@hp = hp
end
def self.save(name, type,db)
db.execute("INSERT INTO pokemon (name, type) VALUES (?, ?)",name, type)
end
def self.find(id,db... |
require 'rails_helper'
describe UserExamPolicy do
let(:user) { User.new }
subject { UserExamPolicy }
permissions :new?, :start? do
before do
FactoryGirl.create :user
FactoryGirl.create :course
FactoryGirl.create :attending
FactoryGirl.create :lesson_category
FactoryGirl.creat... |
Metasploit::Model::Spec.shared_examples_for 'Module::Target::Platform' do
context 'factories' do
context module_target_platform_factory do
subject(module_target_platform_factory) do
FactoryGirl.build(module_target_platform_factory)
end
it { should be_valid }
context '#module_targ... |
class Event < ApplicationRecord
has_many :menus
end
|
class CharactersCreateSkills < ActiveRecord::Migration
def change
create_table :skills do |t|
t.references :owner, polymorphic:true
t.string :code
t.string :name
t.string :aspect
t.integer :level
end
add_index :skills, :code
end
end
|
class AddAreaTypeToAreas < ActiveRecord::Migration
def change
add_column :areas, :area_type, :string
end
end
|
require_dependency 'library_entry_query'
class HomeController < ApplicationController
def index
if user_signed_in?
redirect_to '/dashboard'
else
render_ember
end
end
def dashboard
unless user_signed_in?
redirect_to root_url
return
end
recent_library_entries = Lib... |
class UrlsController < ApplicationController
before_action :set_url, only: [:show, :edit, :update, :destroy]
#respond_to :html, :json
def new
@page_title = "Add New Video Link"
@url = Url.new
@tags = Tag.new
authorize @url
end
def edit
@page_title = "Edit Link"
@url = Url.find(par... |
class MasterLeasePdfForm < FillablePdfForm
def initialize(tenant)
@tenant = tenant
super()
end
protected
def fill_out
[:tenantname, :t_address, :tenantbuildinginfo, :t_email, :t_phone, :propertynumber, :leasestart, :leaseend, :monthrent2, :addterms, :businesstype, :renewterms].each do |field|
... |
class Session
include Mongoid::Document
include Mongoid::Timestamps
field :session_token, type: String
field :is_logged_out, type: Boolean, default: false
belongs_to :user, index: true
before_create :generate_session_token
def generate_session_token
self.session_token = loop do
random_token = ... |
require 'spec_helper'
RSpec.describe ApiPresenter::Base do
let(:current_user) { User.new }
let(:relation) { double('relation') }
let(:count_param) { nil }
let(:include_param) { nil }
let(:policies_param) { nil }
let(:params) { { count: count_param, include: include_param, policies: policies_param } }
le... |
require 'rails_helper'
RSpec.describe PanelProvider, type: :model do
it { should validate_presence_of(:code) }
describe "code uniqueness" do
subject { PanelProvider.new(code: "pan1") }
it { should validate_uniqueness_of(:code) }
end
it { should have_many(:target_groups).with_foreign_key('panel_prov... |
class Page < ActiveRecord::Base
belongs_to :site
validates :title, presence: true, length: { maximum: 100 }
validates :template, presence: true, length: { maximum: 100 }
validates :path, presence: true, length: { maximum: 100 },
format: { with: %r!\A/! }
validates :data, length: { maximum: ... |
require 'rails_helper'
RSpec.describe PodcastsController, type: :controller do
include ActiveModelSerializers::Test::Serializer
describe "GET #index" do
let!(:podcasts) { create_list(:podcast, 10) }
let!(:content) do
content = Content.new
content.podcasts = podcasts
content
end... |
class ApplicationController < ActionController::Base
require 'will_paginate/array'
before_action :authenticate_user!
rescue_from CanCan::AccessDenied do |exception|
redirect_to new_user_session_path, :alert => exception.message
end
private
def current_ability
controller_name_segments = params[:c... |
class AddInstockToProduceOrderItems < ActiveRecord::Migration
def change
add_column :produce_order_items, :instock, :decimal
add_column :produce_order_items, :remark, :text
end
end
|
require 'spec_helper'
describe 'python::requirements', type: :define do
let(:title) { '/requirements.txt' }
context 'on Debian OS' do
let :facts do
{
id: 'root',
kernel: 'Linux',
lsbdistcodename: 'squeeze',
osfamily: 'Debian',
operatingsystem: 'Debian',
op... |
class Performer < ActiveRecord::Base
has_many :performances
end
# == Schema Info
# Schema version: 20110328181217
#
# Table name: performers
#
# id :integer(4) not null, primary key
# created_at :datetime
# updated_at :datetime
# name :string(50) not null, default(" ") |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name =>... |
# encoding: utf-8
control "V-92697" do
title "The Apache web server must be tuned to handle the operational requirements of the hosted application."
desc "A denial of service (DoS) can occur when the Apache web server is so overwhelmed that it can no longer respond to additional requests. A web server not properly t... |
class WeeklySummaryMailer < ApplicationMailer
FRIDAY_LAST_WEEK = Date.today - 7.days
def send_weekly_summary tasks_completed
@start_of_the_week = FRIDAY_LAST_WEEK
@end_of_the_week = Date.yesterday
@start_of_the_week_formatted = @start_of_the_week.strftime '%m/%d/%Y'
@end_of_the_week_formatted = ... |
class Blog < ActiveRecord::Base
attr_accessible :title, :url
has_many :articles
def self.find(url)
find_by_url(url)
end
def to_param
url
end
end
|
require 'spec_helper'
describe Note do
it "should get random records by annotation" do
n = Note.create(:language => "english")
Note.get_random_by_language("english").first.id.should == n.id
n.annotations.create
n.approved_counter += 1
n.save
Note.get_random_by_language("english").first.i... |
require "test_helper"
describe VideosController do
describe "index" do
it "must get index" do
get videos_path
must_respond_with :success
expect(response.header['Content-Type']).must_include 'json'
end
it "will return all the proper fields for a list of videos" do
video_fields ... |
module Tessera
class Ticket
class << self
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
def find(ticket_id)
ticket = if ticket_id.is_a? Array
::Tessera::Api::TicketList.call(ticket_id)
else
::Tessera::Api::... |
class Owner
attr_accessor :pets , :name
attr_reader :species
@@all = []
def initialize(pets)
@species = "human"
@pets = {fishes: [], cats: [], dogs: []}
@@all << self
end
def self.all
@@all
end
def self.count
self.all.count
end
def self.reset_all
self.all.clear
end
def say_species
"I a... |
class CreateUserMovieStatuses < ActiveRecord::Migration[5.0]
def change
create_table :user_movie_statuses do |t|
t.belongs_to :user
t.date :schedule_date
t.timestamps
end
end
end
|
class Post < ActiveRecord::Base
scope :latest, -> { limit(10) }
scope :sorted, -> { order('published_at DESC') }
scope :published, -> { where(draft: false) }
def self.search(query)
# where(:title, query) -> This would return an exact match of the query
where("body LIKE? OR subject LIKE?", "%#{query}%",... |
require 'test_helper'
class CasaTest < ActiveSupport::TestCase
test 'line one should be present' do
address=build(:casa,line_one:nil)
assert_not address.valid?
end
test 'state should be present' do
address=build(:casa,state:nil)
assert_not address.valid?
end
test 'zip should be present' do
... |
module Api
module V1
class ActiveProductsController < ApplicationController
before_action :set_resources
before_action :disable_outdated_content, only: :index
def index
@products = @user.alive_products
respond_with(@products)
end
private
def set_resources
... |
require 'spec_helper'
describe RelationshipsController do
describe "POST new" do
it_behaves_like "requires_signed_in_user" do
let(:action) { post :create, followed_id: Fabricate(:user).id }
end
let(:bob) { Fabricate(:user) }
let(:alice) { Fabricate(:user) }
before do
set_current_user(... |
class Project < ApplicationRecord
validates :name, :due_date, presence: true
# validates :name, exclusion: { in: %w(% *),
# message: "%{value} is reserved." }
# belongs_to :user
# validates :public_notice, acceptance: { message: 'must be checked!!!' }
has_many :tasks
validates_associated ... |
# check that adding new suggested relation ships doesn't violate transitive similarity
require_relative '../../test_helper'
class Bot::AlegreRelationshipTest < ActiveSupport::TestCase
def setup
super
ft = DynamicAnnotation::FieldType.where(field_type: 'language').last || create_field_type(field_type: 'langua... |
# frozen_string_literal: true
module EsaArchiver
module Entities
EsaPost = Struct.new(:number, :category, :message, :created_by) do
def archived_category
"Archived/#{category}"
end
end
end
end
|
module LayoutHelper
# Nested Layouts Helper
def parent_layout(layout)
render :template => "layouts/#{layout}"
end
# Set title
def title(page_title, show_title = true)
content_for(:title) { h(page_title.to_s) }
@show_title = show_title
end
def show_title?
@show_title
end
... |
require 'rails_helper'
RSpec.describe UserContact, type: :model do
it "UserContact is valid when email is unique and present, name is present" do
user_contact = UserContact.new(email: "test@test.com.br", name: "Contact Test")
expect(user_contact).to be_valid
end
it "UserContact is invalid when email is... |
describe Game do
subject { described_class.new(frame_class: frame_class, score_board: score_board) }
let(:frame) { instance_double(Frame, :frame, add_roll: nil, over?: false) }
let(:frame_class) { class_double(Frame, :frame_class, new: frame) }
let(:score_board) { class_double(ScoreBoard, :score_board, total_s... |
require_relative 'page_objects/change_password_page'
require_relative 'page_objects/home_page'
require_relative 'page_objects/login_page'
require_relative 'page_objects/my_account_page'
require_relative 'page_objects/register_page'
require_relative 'page_objects/projects_page'
# require_relative 'user'
#rspec spec/lib... |
require 'test_helper'
class I18nBackendEnvVarLookupTest < Test::Unit::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::EnvVarLookup
end
def setup
ENV['APP_NAME'] = 'Foo Bar'
I18n.backend = Backend.new
I18n.backend.store_translations(:en,
:foo => 'foo',
:bar => {
... |
class UsersController < ApplicationController
before_action :find_user, only: [:show, :update, :edit, :destroy]
def index
@users = User.all
end
def show
end
def edit
end
def update
@user.update(user_params)
redirect_to current_user
end
def destroy
@user.destroy
redirect_to... |
class ApplicationController < ActionController::Base
include CanCan::ControllerAdditions
before_action :configure_permitted_parameters_name, if: :devise_controller?
protect_from_forgery with: :exception
before_filter :user_access_log
def alipay_client
client = Alipay::Client.new(
url: ENV['ALIPA... |
module SimpleHdGraph
module Renderer
module PlantUML
class Context
def initialize
@resource_renderer = Resource.new
end
#
# @param node [ContextNode]
#
# :reek:FeatureEnvy, :reek:DuplicateMethodCall
def render(node)
resources = nod... |
class Array
def to_hash
each_with_object({}) do |pair, hash|
hash[pair.first] = pair[1]
hash
end
end
def index_by
map { |n| [yield(n), n] }.to_hash
end
def subarray_count(subarray)
each_cons(subarray.length).count(subarray)
end
def occurences_count
each_with_object(Hash.... |
#
# This file was ported to ruby from Composer php source code file.
# Original Source: Composer\Package\RootAliasPackage.php
#
# (c) Nils Adermann <naderman@naderman.de>
# Jordi Boggiano <j.boggiano@seld.be>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed wit... |
module OAuth2Provider
module Tokens
class Base
DEFAULT_EXPIRE_TIME = 60*60*24*90 # in seconds (90 days)
EPOCH = 1293840000
attr_reader :client, :owner, :scope, :refresh_token
attr_accessor :expires_in, :created_at
def self.unserialize(value)
owner_id, client_key, scope, cre... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_cart
def current_cart
if !session[:cart_id].nil?
Cart.find(sessions[:cart_id])
else
Cart.new
end
end
private
helper_method :current_user
def current_user
@curren... |
class DropSearchSuggestions < ActiveRecord::Migration[5.1]
def change
drop_table :search_suggestions
end
end
|
class AddLtiInstallIdToLtiDeployments < ActiveRecord::Migration[5.2]
def change
add_reference :lti_deployments, :lti_install, foreign_key: true
end
end
|
# This program will compose a tweet from the terminal
# Make sure your twitter api has read and write capabilities enabled!
# Remember to enter your API Tokens!
require 'rubygems'
require 'oauth'
require 'json'
# Please enter your api credentials here
consumer_key = OAuth::Consumer.new(
"Enter API Key",
"Enter AP... |
class CreateReadings < ActiveRecord::Migration
def change
create_table :readings do |t|
t.integer :account_id
t.integer :usage
t.datetime :read_at
t.string :read_type
t.timestamps
end
end
end
|
class AnnouncementsController < ApplicationController
respond_to :html, :json
def index
@announcements = Announcement.all
respond_with @announcements
end
def new
@announcement = Announcement.new
respond_with @announcement
end
def show
@announcement = Announcement.find_by(id: params[:i... |
class Product < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
validates :name, presence: true,
length: { minimum: 3 }
validates :description, presence: true
validates :description, presence: true
validates :iteminexchange, presence: true
mount_uploader :pict... |
#!/usr/bin/env ruby
require 'fileutils'
module Build
BUILD_DIR='build'
C_FILES = Dir['mods/core/src/*.c'] +
Dir['src/*.c']
CC='clang'
CFLAGS=%w{-Wall -Werror -Wextra -O3 -std=c99}
INCLUDES=[
'mods/core/inc',
'inc',
].map {|i| "-I" + i}
PROG='ckvs'
OUTPUT=File.join(BUILD_DIR, PROG... |
class UsersController < ApplicationController
before_action :authenticate_user!
def index
@user = User.all
end
def show
#matches show.html.erb under views/users
@user = User.find( params[:id] ) #just id NOT :user_id since url structure is /:id not /:userid in rake routes
... |
#!/usr/bin/env ruby
# http://projecteuler.net/problem=9
def pythagorean_triplet(sum)
(1...sum).each do |c1|
(c1.succ...sum).each do |c2|
h = (sum - c1 - c2)
# return triplet if h is really the hypotenuse
return [c1, c2, h] if (h * h) == (c1 * c1 + c2 * c2)
end
end
end
product = pythago... |
require './startup'
class SunRiseSet
attr_reader :zip, :page
def initialize(zip)
@zip = zip
@page = get_data
end
def sun_time(type)
hour = @page["sun_phase"][type]["hour"]
minute = @page["sun_phase"][type]["minute"]
"#{type} time is: #{hour}:#{minute}"
end
private def get_data
HT... |
require "test_helper"
class VoteTest < ActiveSupport::TestCase
def setup
@user = User.new(name: 'Chris',
email: 'chris@example.com',
password: 'welcome1',
password_confirmation: 'welcome1')
@poll = Poll.new(title: 'This poll is for testing purpose',... |
require 'erb'
module Services
class QuestionPrinter
attr_reader :conversation_strategy, :conversation
delegate :current_state, to: :conversation_strategy
delegate :user, to: :conversation
def initialize(conversation_strategy, conversation:)
@conversation_strategy = conversation_strategy
... |
module Domotics::Core
class ElementGroup < BasicObject
attr_reader :name, :type, :room, :elements
def initialize(args = {})
#::Object.instance_method(:is_a?).bind(self)
@name = args[:name] || :undefined
@room = Room[args[:room]]
@room.register_element self, @name
@elements = []
... |
class Step < Resource
#validates_presence_of :title
#validates_presence_of :name, :if => :title
#validates_uniqueness_of :name
fortify :title, :name
belongs_to :definition
has_many :messages
delegate :roles, :to => :definition
#has_many_siblings :reaction, :cause => :effect
#has_many :recip... |
Puppet::Type.type(:bsd_interface).provide(:openbsd, :parent => :ifconfig) do
confine :kernel => [:openbsd]
defaultfor :kernel => [:openbsd]
commands :sh => 'sh'
def restart
sh('/etc/netstart', resource[:name])
end
end
|
class ContactSearch
attr_reader :query, :user
def initialize(query:, user:)
@query = query
@user = user
end
def results
@results ||= Contact.search(
query,
fields: fields,
where: where,
misspellings: misspellings,
limit: 5
)
end
private
def where
{user... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.