text stringlengths 10 2.61M |
|---|
class Cat < ApplicationRecord
CAT_COLORS = [
"Black",
"White",
"Striped",
"Orange"
]
end |
class Rating < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
end
|
module Secretary
class Config
DEFAULTS = { user_class: "::User" }
# Pass a block to this method to define the configuration
# If no block is passed, config will be defaults
def self.configure
config = new
yield config if block_given?
Secretary.config = config
end
#-... |
require_relative 'lib/task'
namespace :viky do
desc "Setup database and statistics"
task :setup => [:environment] do |t, args|
# Database related
connected = ::ActiveRecord::Base.connection_pool.with_connection(&:active?) rescue false
if connected
if ::ActiveRecord::SchemaMigration.table_exists?... |
require 'lib/air_monitor'
require 'lib/rom'
require 'lib/user_repository'
include Facebook::Messenger
NORM = 50
user_repository = UserRepository.new(CONTAINER)
Bot.on :message do |message|
message.typing_on
user = find_or_create(user_repository, message.sender['id'])
station_code = message.quick_reply
if ... |
namespace :iq do
namespace :upload do
desc 'Clear all auto generated files and database entries'
task :purge_versions => :environment do
# Get Rails to load the models
Dir.glob(File.join(RAILS_ROOT, 'app/models/**/*.rb')).each do |file|
File.basename(file, '.rb').classify.constantize
... |
class AddToCart < Rectify::Command
attr_reader :order, :book_id, :quantity
def initialize(order, params)
@order = order
@book_id = params[:book_id]
@quantity = params[:quantity].to_i
end
def call
if order_item.valid? && order_item.save && order.save
broadcast :valid, quantity
else
... |
class ProjectsController < ApplicationController
before_action :logged_in_user
def index
@project = Project.find(params[:id])
end
def new
@project = Project.new
end
def edit
@project = Project.find(params[:id])
end
def update
@team = Team.find(params[:team_id])
@project = Project... |
json.array!(@posts) do |post|
json.extract! post, :id, :name, :free, :price, :obo, :expiredate, :tix_eventname, :tix_eventdate, :tb_classname, :tb_classnumber, :tb_edition
json.url post_url(post, format: :json)
end
|
class Gene
def initialize()
@data = nil
@val = 0.0
@eval = 0.0
end
attr_accessor :data,:val,:eval
def to_s
return "#{@data}, #{@val} , #{@eval}"
end
end |
require 'maws/command'
require 'maws/elb_command'
require 'maws/trollop'
class ElbEnableZones < ElbCommand
def description
"elb-enable-zones - add entire zones to specified ELBs (zones must exist)"
end
def add_specific_options(parser)
parser.opt :zones, "Zones to enable", :short => '-z', :type => :stri... |
require "open-uri"
#draws on supplier_csv_import.rake heavily
#current sheet: https://docs.google.com/a/supplybetter.com/spreadsheets/d/1B3PBeMXKGvT6lUuDdt5v7VrbxBKva0SAEcRgppDZqIc/edit#gid=469578003
desc 'import providers from csv'
task :provider_csv_import => :environment do
c = Contact.where("email = ?","peter@f... |
class ItemsController < ApplicationController
def index
@items = Item.all
end
def new
@item = Item.new
end
def create
@item = Item.new(item_params)
@item.save
redirect_to admins_home_path
end
private
def item_params
params.require(:item).permit(:title, :price)
end
end
|
class Api::V1::Unauthorised < Api::V1::Error
def initialize(friendly_error_message=nil)
self.friendly_error_message = friendly_error_message
super("Unauthorised access")
end
def internal_error_code
6
end
def http_status
401 # Unauthorised
end
def friendly_error_message
@friendly_err... |
# encoding: utf-8
$: << 'RspecTests/Generated/azure_url'
require 'rspec'
require 'securerandom'
require '2014-04-01-preview/generated/subscription_id_api_version'
include AzureUrlModule
describe Group do
before(:all) do
@base_url = ENV['StubServerURI']
dummyToken = 'dummy12321343423'
... |
require 'rails_helper'
require 'bundler/settings'
require 'helpers/authentication_helper'
describe 'visiting the homepage', type: :feature do
it 'user can create a goal' do
givenIAmOnTheHomepage
whenIClickCreateGoalCallToAction
whenIAuthorizeWithFacebook
thenIAmLoggedIn
thenIAmOnTheGoalCreationPa... |
h = {a:1, b:2, c:3, d:4}
#1. Get the value of key `:b`.
#
#2. Add to this hash the key:value pair `{e:5}`
#
#3. Remove all key:value pairs whose value is less than 3.5
puts "Starting with the hash:"
p h
# 1
puts "1. Get the value of ':b':"
p h[:b]
# 2
puts "2. add {e:5} to the hash:"
h[:e] = 5
p h
# 3
h.each do |k... |
class CreateProposals < ActiveRecord::Migration
def change
create_table :proposals do |t|
t.string :proposal_number
t.string :provision_number_name
t.string :map_number
t.string :submission_type
t.text :submission_details
t.string :decision_type
t.text :reasons
t.in... |
require "spec_helper"
describe Item do
context "is not valid without "
it "a name" do
subject.should_not be_valid
subject.errors[:name].should_not be_empty
end
it "description" do
subject.name = "Mocha"
subject.should_not be_valid
subject.errors[:description].should_not be_empty
end
end |
class DeleteAdminMessageCommand
include ActiveEvent::Command
attributes :id
end
|
Factory.define :user do |f|
f.sequence(:username) { |n| "Tom #{n}"}
f.sequence(:email) { |n| "test@email#{n}.com"}
f.password "666666"
f.password_confirmation "666666"
end
Factory.define :role do |f|
f.name "Superman"
end
Factory.define :snippet do |f|
f.sequence(:title) ... |
module Funl::HistoryWorker
attr_reader :history
def initialize client
super
@history = client.history_size && Array.new(client.history_size)
# nil in case of use without UDP
end
def record_history msg
history[global_tick % history.size] = msg if history
end
end
|
class WorkoutExerciseSerializer < ActiveModel::Serializer
attributes :id, :name, :difficulty, :how, :length, :reps, :category
def category
object.exercise.category.name
end
end
|
class AddGourlToBaner < ActiveRecord::Migration
def change
add_column :baners, :gourl, :text
end
end
|
class User < ApplicationRecord
validates :name, presence: true
validates :email, presence: true, uniqueness: true
validates :password, presence: true, on: :create
has_many :sent_transactions, class_name: "Transaction", foreign_key: "sender_id"
has_many :received_transactions, class_name: "Transaction",... |
require 'rufus-scheduler'
unless Rails.env.test?
scheduler = Rufus::Scheduler.new
scheduler.every '15m', first_in: '5s' do
Rails.logger.info "Beginning FitBit update at #{Time.now}"
config = begin
yaml_template = ERB.new(File.new('.fitgem.yml.erb').read)
Fitgem::Client.symbolize_keys(YAML.loa... |
BASKET_DISCOUNT = 0.1
DISCOUNT_THRESHOLD = 60
MULTIBUY_PRICE = 8.5
LOWER_BASKET_TOTAL = 55
BASKET_TOTAL = 65
TEN_PERC_BASKET = BASKET_TOTAL*0.9
PRODUCT_CODE_ONE = "001"
ITEM_NAME_ONE = "Travel Card Holder"
ITEM_PRICE_ONE = 9.25
def doubles
let(:promotional_rules) {double(:promotion,
... |
require 'spec_helper'
describe Schedule, 'validations' do
context 'when valid data' do
let!(:user) { create(:user, :paul) }
let!(:event) { create(:event, :tasafoconf, users: [user], owner: user) }
let!(:schedule) { create(:schedule, :abertura, event: event) }
it 'accepts valid attributes' do
e... |
class Admin::BaseController < ApplicationController
before_action :authorized_manage
before_action :signed_in_user
layout "admin"
load_and_authorize_resource
private
def authorized_manage
redirect_to root_path unless current_user.is?(:manager) || current_user.is?(:admin)
end
end
|
class Comment < ActiveRecord::Base
attr_accessible :comment_id, :content, :like, :msg_id, :time, :user_id, :user_name
validates_uniqueness_of :comment_id
serialize :like, Array
belongs_to :msg
end
|
class ControllerEn < Controller
attr_reader :game_options_array, :player, :dealer, :view
def initialize
super
@view = ViewEn.new
end
# game and round methods
def start_round
super
@game_options_array = ['Skip', 'Take card', 'Open up']
end
# player methods
def player_skip_turn!
@... |
class HomePage
def initialize(driver)
@driver = driver
end
def verify_page
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { @driver.find_element(:id => 'lbl-val_1') }
end
def count_values
iCountvalues = @driver.find_elements(id: "lbl_val_").size;
iCounttext = @driver... |
require_relative 'models/user'
require_relative 'models/game'
require_relative 'util.rb'
module Jeoparty
module Hooks
# Hook when reactions are added. Used as a shortcut for
# judges and category shuffling
class ReactionAdded
def call(client, data)
game = Channel.get(data['item']['channel']... |
class MultiTransactionFine < ActiveRecord::Base
has_many :finance_transaction_fines
has_many :finance_transactions, :through => :finance_transaction_fines
belongs_to :receiver, :polymorphic => true
attr_accessor :fee_id, :fee_type
validates_presence_of :amount
validates_presence_of :fee_id
validates_numer... |
class Expense < ApplicationRecord
validates :user, :datetime, :amount, presence: true
belongs_to :user
end
|
class User
include Mongoid::Document
include Mongoid::Timestamps
include ActiveModel::SecurePassword
field :password_digest, type: String
field :email, type: String
field :last_signed_in, type: ActiveSupport::TimeWithZone
has_secure_password
# Updates the user's login related information, such as the... |
class Hangman
attr_accessor :words, :word
def initialize(word=nil)
# @words = ['banana', 'apple', 'technodrome']
# @word = word
# @word ||= words.sample
@guesses = []
@turns = 7
contents = File.read '/usr/share/dict/words'
words = contents.split
good_words = words.select ... |
# frozen_string_literal: true
module EasyMonitor
module Util
module Errors
class NotWorking < StandardError
def initialize(msg = 'Not working error', class_name = nil)
msg += " for class #{class_name}" if class_name
super(msg)
end
end
end
end
end
|
require 'rubygems'
require "xmpp4r"
require "xmpp4r/pubsub"
require "xmpp4r/pubsub/helper/servicehelper.rb"
require "xmpp4r/pubsub/helper/nodebrowser.rb"
require "xmpp4r/pubsub/helper/nodehelper.rb"
module Commonsense
module Xmpp
class NodePublisher
def self.publish
include Jabber
Jabber:... |
def first_anagram?(str1, str2)
strings = str1.split("")
words = strings.permutation.to_a #O(n!)
subs = []
words.each do |word| #O(n)
subs << word.join("")
end
subs.include?(str2) #O(n)
end
#=> O(!n!)
def second_anagram?(str1, str2)
str2_chars = str2.split("")
str1.each_char do |char| #O(n)... |
# frozen_string_literal: true
module BCommerce
module ServerToServer
class Cart < Resource
PATH = '/carts'
API_VERSION = 'v3'
attribute :customer_id, type: Integer
attribute :line_items, type: Array, validate_with: :validate_line_items
attribute :gift_certificates, type: Array, vali... |
class Movie < ActiveRecord::Base
belongs_to :users
validates :title, length: {minimum: 1, maximum:50}
validates :length, numericality: {greater_than: 0, less_than: 500, only_integer: true}
validates :release_year, numericality: {greater_than: 1800, less_than: 2100, only_integer: true}
end
|
# frozen_string_literal: true
FactoryBot.define do
trait :active do
expired_at nil
end
factory :session do
expired_at { 3.days.ago }
end
end
|
module ProfileHelper
def panel_profile
case request.path
when /^\/wizard/
:wizard
when /^\/panel/
:panel
when /^\/editor/
:editor
else
session[:panel_profile] ||= :user
end
end
def panel_profile=(profile)
session[:panel_profile] = profile.to_sym unless profil... |
class Status < ApplicationRecord
validates :label, presence: true, uniqueness: true
end
|
class ActiveRecord::Base
def self.find_random(options = {})
options = options.dup
options[:order] = 'RAND()'
options[:limit] ||= 1
self.find(:all, options)
end
end
|
# frozen_string_literal: true
module Decidim
module Opinions
module Metrics
class EndorsementsMetricManage < Decidim::MetricManage
def metric_name
"endorsements"
end
def save
cumulative.each do |key, cumulative_value|
next if cumulative_value.zero?
... |
class CreateBill < ActiveRecord::Migration
def change
create_table :bills, id: false do |t|
t.uuid :id, :primary_key => true, default: "uuid_generate_v4()"
t.uuid :developer_id
t.date :start
t.date :end
t.string :type
t.integer :state
t.integer :amount
t.bigint ... |
# frozen_string_literal: true
require "dry/logic/predicates"
RSpec.describe Dry::Logic::Predicates do
describe "#lt?" do
let(:predicate_name) { :lt? }
context "when value is less than n" do
let(:arguments_list) do
[
[13, 12],
[13.37, 13.36]
]
end
it_be... |
module ThirdBase
class Railtie < Rails::Railtie
config.third_base = ActiveSupport::OrderedOptions.new
config.third_base.path = 'db/thirdbase'
config.third_base.config_key = 'thirdbase'
config.third_base.run_with_db_tasks = true
config.after_initialize do |app|
thirdbase_dir = app.root.join... |
# https://www.mm2d.net/main/prog/c/console-02.html
# ANSI_escape_code という仕組みを使うとカラーで出力できる
puts "this is plain"
print "\e[31m"
puts "this is red"
print "\e[0m"
puts "\e[34mthis is blue\e[0m"
module Color
def self.red str
return "\e[31m#{str}\e[0m"
end
def self.green str
return "\e[32m#{str}\e[0m"
en... |
input = File.read("input").split(',').map(&:to_sym)
dirs = {
n: {x: 0, y: 1},
ne: {x: 0.5, y: 0.5},
se: {x: 0.5, y: -0.5},
s: {x: 0, y: -1},
sw: {x: -0.5, y: -0.5},
nw: {x: -0.5, y: 0.5}
}
def get_min_steps(pos)
x_steps = pos[:x].abs * 2
y_steps = pos[:y].abs * 2
if x_steps >= y_steps
... |
class CreateMailLogRecipientLists < ActiveRecord::Migration
def self.up
create_table :mail_log_recipient_lists do |t|
t.text :recipients
t.integer :mail_log_id
t.integer :recipients_count, :default => 0
t.integer :school_id
t.timestamps
end
add_index :mail_log_recipient_... |
require "airtable_plus/version"
require 'airtable'
require 'active_support/all'
class AirtablePlus
autoload 'Mapper', 'airtable_plus/mapper'
DEFAULT_ID_FIELD = 'id'.freeze
attr_accessor :mapper
attr_accessor :records
attr_accessor :id_field
def initialize(api_key, app_id, worksheet_name)
... |
require_relative "../../../lib/commands/init_bitmap"
RSpec.describe Commands::InitBitmap do
describe '#new' do
subject { Commands::InitBitmap.new(args: args) }
let(:m) {3}
let(:n) {4}
let(:args) { [m, n] }
context 'valid params' do
context 'm = 1 and n = 1' do
let(:m) { 1 }
... |
module Belafonte
module Helpers
# Instance methods for apps
module Restricted
protected
def activate_help!
@help = true
end
private
def help
@help ||= false
end
def help_active?
help
end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Friendship, type: :model do
before :each do
@user1 = User.create(first_name: 'daniel', last_name: 'addo', email: 'daniel@test.com', password: '123456')
@user2 = User.create(first_name: 'nick', last_name: 'haras', email: 'nick@test.com', pas... |
require 'test/unit'
require 'bencode'
class TC_Bencode < Test::Unit::TestCase
def test_string
assert_equal("4:spam", bencode("spam"))
end
def test_emptystring
assert_equal("0:", bencode(""))
end
def test_number
assert_equal("i3e", bencode(3))
end
def test_negative_number
assert_equal("... |
class FavoriteController < ApplicationController
respond_to :json, :js, :html
def favorite
return unless current_user
# get IDs of companies that are currently favorited
user_favorite_active = current_user.favorite_companys.where(active: true).map(&:company_id)
# Set the current user companies to t... |
require 'puppet'
require 'rest_client'
require 'json'
Puppet::Reports.register_report(:jpuppetboard) do
def process
Puppet.info "Starting Report Processing"
begin
RestClient.post 'http://localhost:8080/api/reports', get_report, :content_type => :json, :accept => :json
rescue
raise Puppet::Err... |
# Counting Up
=begin
(Understand the Problem)
Problem:
Write a method that takes an integer argument, and returns an Array of all integers, in sequence, between 1 and the argument
Inputs: Integer
Outputs: Array (containing integers in sequence, between 1 and the input Integer)
Questions:
1.
Explicit... |
class AddStateIdToCities < ActiveRecord::Migration
def change
add_column :cities, :state_id, :string
end
end
|
# How to use:
# run cmd: "ruby max_drawdown_by_account_balance.rb name_of_csv_file.csv"
account_balances = []
File.read("./#{ARGV[0]}").lines.each do |row|
account_balances << row.to_i
end
running_max_account_balance = 0
running_min_account_balance = 0
running_max_drawdown = 0
running_max_upside = 0
running_max_dra... |
class CreateEncontros < ActiveRecord::Migration[5.0]
def change
create_table :encontros do |t|
t.string :titulo
t.string :descricao
t.string :tema
t.date :inicio_inscricoes
t.date :fim_inscricoes
t.date :inicio_encontro
t.date :fim_encontro
t.decimal :valor
t.... |
activate :automatic_image_sizes
activate :directory_indexes
activate :livereload
set :markdown_engine, :redcarpet
set :markdown, fenced_code_blocks: true, smartypants: true
helpers do
def slugify(string)
string.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
end
end
set :css_dir, 'assets/stylesheets'
set :j... |
#---
# Excerpted from "Agile Web Development with Rails, 4rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any pur... |
class ProposalPolicy
class Scope
def initialize(user, scope)
@user = user
@scope = scope
end
# returns the entire list of Proposals that are visible to the user
def resolve
if @user.admin?
@scope.all
elsif @user.client_admin?
for_client_admin
else
... |
class CreatePassionCareers < ActiveRecord::Migration
def change
create_table :passion_careers do |t|
t.references :passion, index: true
t.references :career, index: true
t.text :description
t.timestamps
end
end
end
|
require_relative 'spec_helper'
describe 'Tubular::Bencode' do
it "can parse integers" do
parsed = Tubular::Bencode.parse_from_string("i42e")
parsed.must_equal 42
end
it "can parse strings" do
parsed = Tubular::Bencode.parse_from_string("11:hello world")
parsed.must_equal "hello world"
end
... |
Rails.application.routes.draw do
get 'search/create'
devise_for :users
root 'questions#index'
resources :comments
resources :answers
resources :questions do
member do
put "Upvote", to: "questions#upvote"
put "Downvote", to: "questions#downvote"
end
resources :comments
end
# For det... |
class CampaignSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :public, :selected_encounter
has_one :dm
has_one :channel
has_many :users
has_many :encounters
end
|
Rails.application.routes.draw do
get "/superheroes", to:'super_heroes#index'
get "/superheroes/:id", to: 'super_heroes#show'
post "/superheroes", to:'super_heroes#create'
patch "/superheroes/:id", to: 'super_heroes#update'
delete "/superheroes/:id", to: 'super_heroes#destroy'
namespace :api do
namespace :v1 do... |
class PublicProjectSerializer < ProjectSerializer
attributes :name,
:state,
:public_viewable,
:members_count,
:segments_count,
:created_at,
:updated_at,
:collaborators_description,
:segments,
:total_du... |
class AddUniqueIndexToOnlineExamGroupsQuestions < ActiveRecord::Migration
def self.up
add_index :online_exam_groups_questions, [:online_exam_question_id,:online_exam_group_id],:unique=>true, :name=>:groups_questions_unique_index
end
def self.down
remove_index :online_exam_groups_questions,:name=>:groups_... |
class Post < ActiveRecord::Base
validates :slug, uniqueness: true
validates :title, presence: true
validates :content, presence: true
scope :published, -> { where(published: true).order('published_at DESC') }
scope :ideas, -> { where(published: false) }
def idea?
!published
end
def statu... |
class Pattern
attr_reader :first_name, :last_name
class << self
def build(name)
new *name.split(/[.|\s[1]]/)
end
end
def initialize(first_name, last_name)
@first_name, @last_name = first_name, last_name
end
def generate
[first_part, last_part].join('_dot_').to_sym
end
def predi... |
# Linked list program -- short version
class Point
def Point.new(x, y)
super.init(x, y)
end
def init(x, y)
@x = x; @y = y
self
end
def to_s
sprintf("%d@%d", @x, @y)
end
end
list1 = [10, 20, Point.new(2, 3), Point.new(4, 5)]
list2 = [20, Point.new(4, 5), list1]
print("list1:\n", list1.... |
#encoding: UTF-8
class Author < ActiveRecord::Base
has_and_belongs_to_many :stories
def full_name
"#{self.first_name} #{self.last_name}"
end
validates :first_name, :uniqueness => { :scope => :last_name}
validates :first_name, :presence => {:message => 'Musisz podać imię autora.'}
validates :last_name, ... |
#!/usr/bin/env ruby
#codebar.oi tutorials
#Introduction to Ruby
#Number game
#x and y are random numbers
x = 0
y = 0
answer = 0
turns = 0
right = 0
wrong = 0
starting = 0
ending = 0
starting = Time.now
print "How many times?"
times = gets.to_i
if times <= 0 || times == nil
times = 1
end
#if times == nil
#... |
Rails.application.routes.draw do
root to: 'tasks#index'
resources :tasks do
member do
post 'complete', to: 'tasks#complete'
end
end
end
|
# frozen_string_literal: true
require 'dry-struct'
require 'bank_deposits/types'
module BankDeposits
class Deposit < Dry::Struct
attribute :name, Types::Coercible::String.constrained(min_size: 1)
attribute :currency, Types::Currency
attribute :interest_rate, Types::InterestRate
attribute :annual_com... |
class User < ApplicationRecord
has_many :exercise_entries
has_many :meal_entries
has_many :weight_entries
has_many :recipes
has_secure_password
validates :email, uniqueness: true
validates :email, presence: true
validates :password, presence: true
end
|
class Zoo
include Enumerable
attr_accessor :animals, :name
def initialize (name)
@name = name
@animals = []
end
def addAnimals (*animals)
@animals += animals
end
def to_s
"The #{name} has #{animals.join(", ")}"
end
def each
@animals.each { |animal| yield animal}
end
end |
# additional copyright info:
# the metaprogramming for generate_single_value_readers and
# generate_multi_value_readers was published 2008 by Ernie Miller on
# http://erniemiller.org/2008/04/04/simplified-active-directory-authentication/
# with an excellent explanation.
#
require 'immutable-struct'
module Wobaduser
... |
class AddFdGameWeekToLeagueSeason < ActiveRecord::Migration[5.1]
def change
add_column :league_seasons, :fd_game_week, :integer
end
end
|
class Doctor < ApplicationRecord
validates :name, presence: true
validates :speciality, presence: true
has_many :appointments
has_many :patients, through: :appointments
#belongs_to :users
has_secure_password
mount_uploader :picture, PictureUploader
# Validates the size of an uploaded picture
def... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
hostname="perfo... |
# frozen_string_literal: true
module ActiveAny
class Configuration
attr_accessor :logger, :log_level
def logger
@logger ||= begin
logger = Logger.new($stdout)
logger.level = "::Logger::#{log_level.to_s.upcase}".constantize
logger
end
end
def log_level
@log_... |
class InvoiceSerializer < ActiveModel::Serializer
attributes :id, :customer_id,:sales_order_id, :invoice_dt, :ref_no,
:net_cost, :net_vat, :net_total, :discount_net, :discount_vat,
:discount_total, :transport_net, :transport_vat, :transport_total,
:price_net, :price_vat, :price_total, :full_pallets, :half... |
require 'json'
require File.join(File.dirname(__FILE__), '..', 'nexus_global_config')
Puppet::Type.type(:nexus_application_server_settings).provide(:ruby, :parent => Puppet::Provider::NexusGlobalConfig) do
desc "Ruby-based management of the Nexus web application settings."
confine :feature => :restclient
d... |
class Message < ActiveRecord::Base
belongs_to :author, class_name: 'User'
belongs_to :by_business, class_name: 'Business'
belongs_to :posted_to, polymorphic: true
belongs_to :related_message, class_name: 'Message'
has_many :comments_on, class_name: 'Message', foreign_key: 'related_message_id'
validates_p... |
class AnswerOption < ActiveRecord::Base
include Localizable
has_many :answer_templates, through: :answer_options_answer_templates, join_table: :answr_options_answer_templates
has_many :answer_values
localize :text_value
def value
text_value || time_value || numeric_value
end
end
|
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
describe command('sudo -u vagrant /usr/local/bin/brew info redis --json=v1') do
# the JSON output is awkward to parse here, but it's
# cross-platform-version, since the formula may be installed as a
# source or from bottle depending on the version of OS X.
its(:stdout) { should match('"installed":\[{"version":'... |
class Products
def calculate(number_array)
number_array.each_with_index.map do |num, index|
sub_array = number_array.reject { |num| number_array.index(num) == index }
sub_array.inject(1) { |result, num| result * num }
end
end
end
|
class Assessment < ActiveRecord::Base
belongs_to :exam
belongs_to :organization
has_many :answers
belongs_to :learner, :class_name => "User", :foreign_key => "learner_id"
attr_protected :exam_id, :organization_id, :learner_id
def pass?
unformatted_score >= exam.pass_requirement
end
def score
... |
# Received for MO message or delivery notification
class Smpp::Pdu::DeliverSm < Smpp::Pdu::Base
attr_reader :source_addr, :destination_addr, :short_message, :source_addr, :esm_class, :msg_reference, :stat
def initialize(seq, status, body)
# brutally unpack it
service_type,
source_addr_ton,
source_... |
class Admin::GalleriesController < Admin::AdminController
include PermitConcern
permit gallery: Gallery::PARAMS
def index
@entries =
Gallery
.where(user: current_user)
.paginate(page: params.fetch(:page, 1), per_page: 2)
respond_to do |f|
f.html
end
end
def edit
... |
#==============================================================================#
# ** IEX(Icy Engine Xelion) - Equipment Skills
#------------------------------------------------------------------------------#
# ** Created by : IceDragon (http://www.rpgmakervx.net/)
# ** Script-Status : Addon (Equipment)
# ** Script ... |
class RemoveTimestampsFromRanking < ActiveRecord::Migration[6.1]
def change
remove_column :rankings, :created_at, :string
remove_column :rankings, :updated_at, :string
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.