text stringlengths 10 2.61M |
|---|
module UsersHelper
def user_should_be_able_to_edit_user?(user, editable_user)
user && (editable_user == user || user.is_admin?)
end
end
|
require 'chemistry/element'
Chemistry::Element.define "Calcium" do
symbol "Ca"
atomic_number 20
atomic_weight 40.078
melting_point '1112K'
end
|
class Song
attr_accessor :name, :artist_name
@@all = []
def self.all
@@all
end
def save
self.class.all << self
end
def self.create
song = self.new
song.save
song
end
def self.new_by_name(string_name)
song = self.new
song.name = string_name
song
end
def self.cre... |
class PiecesController < ApplicationController
before_action :find_piece, only: [:show, :edit, :update, :destroy]
def index
end
def new
@piece = Piece.new
end
def create
@piece = Piece.new(permit_piece)
if params[:p_id]
@piece.album_id = params[:p_id]
end
if @piece.save
... |
class Person::AsCreate < Person
after_initialize :create_user
after_initialize :create_contact
private
def create_user
self.user = User.new
end
def create_contact
self.contact = Contact.new
self.contact.emails << Email.new
end
end
|
# frozen_string_literal: true
# Helper to prepare strings with spaces for URLs
def replace_space_with_escape(text)
text.gsub(' ', '%20')
end
# Helper to write pretty JSON to disk
def write_pretty_json(filename, data)
File.open("data/#{filename}", 'w') do |f|
f.write(JSON.pretty_generate(data))
end
end
# Wr... |
# frozen_string_literal: true
require "rails_helper"
RSpec.describe CollaboratorsQuery, type: :query do
describe "#managed" do
let(:company) { create(:company) }
let(:manager) { create(:collaborator, company: company) }
let(:collaborators) do
create_list(:collaborator, 3, manager: manager, compan... |
# frozen_string_literal: true
module Blacklight
class MetadataFieldLayoutComponent < ::ViewComponent::Base
with_collection_parameter :field
with_content_areas :label, :value
# @param field [Blacklight::FieldPresenter]
def initialize(field:, label_class: 'col-md-3', value_class: 'col-md-9')
@fi... |
require "rails_helper"
feature 'User sees card search form', %Q{
As a MTG card player
I want to search for a card
So that I find out more about it.
} do
# [] Visiting the cards_path should show a form for a card
scenario 'user selects Search for a Card' do
visit '/'
click_link 'Search for a Card'
... |
# Квадратное уравнение.
# Пользователь вводит 3 коэффициента a, b и с.
# Программа вычисляет дискриминант (D) и корни уравнения (x1 и x2, если они есть) и выводит значения дискриминанта и корней на экран.
# При этом возможны следующие варианты:
# Если D > 0, то выводим дискриминант и 2 корня
# Если D = 0, то выв... |
FactoryGirl.define do
factory :specialization_category do
factory :technician do
name "Technician"
end
end
end
|
class CreateProductsTags < ActiveRecord::Migration
def change
create_table :products_tags, :id => false do |t|
t.references :product, :tag
end
add_index :products_tags, [:product_id, :tag_id],
name: "products_tags_index"
end
end
|
ActiveAdmin.register AdminUser do
permit_params :email, :timeout, :password, :password_confirmation
controller do
def create
create! { redirect_to :back and return }
end
def update
update! { redirect_to :back and return }
end
end
index do
selectable_column
id_column
c... |
# frozen_string_literal: true
require 'spec_helper'
require 'bolt/plugin/pkcs7'
require 'bolt/util'
describe Bolt::Plugin::Pkcs7 do
around(:each) do |example|
Dir.mktmpdir do |dir|
@boltdir = dir
example.run
end
end
let(:context) do
context = instance_double("Bolt::Plugin::PluginContext... |
#!/usr/bin/env ruby
require File.expand_path(File.join(File.dirname(__FILE__), "../lib/rink"))
def find_class(name, path)
if const = eval(name)
return const
end rescue nil
paths = [path, File.join(path, "lib")]
filename = name.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-... |
FactoryBot.define do
factory :survivor do
name Faker::Name.name
age (Random.new).rand(76)
gender (Random.new).rand(3)
end
end |
class AddRushOrderToDeadline < ActiveRecord::Migration[5.1]
def change
add_column :deadlines, :rush_order, :boolean
end
end
|
describe ProposalUpdateRecorder do
describe "#run" do
context "attribute changed" do
it "adds a change comment" do
description = "some text"
work_order = create(:ncr_work_order, description: description)
work_order.description = ""
comment = ProposalUpdateRecorder.new(work_o... |
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
describe "String UUID" do
it "should have specific format" do
1000.times do
uuid = Util::random_uuid
uuid.should =~ /^#{UUID_RE}$/
end
end
it "should be converted to raw string" do
"00000000-0000-0000-0000-0000000... |
require "language/go"
class Lego < Formula
desc "Let's Encrypt client"
homepage "https://github.com/xenolf/lego"
url "https://github.com/xenolf/lego/archive/v0.4.1.tar.gz"
sha256 "365802c02a7f7106370525444c18af53f010153631f27b7cbeb1b4574631f3e7"
bottle do
cellar :any_skip_relocation
rebuild 1
sh... |
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
require 'ghi/commands/version'
Gem::Specification.new do |s|
s.name = 'ghi'
s.version = GHI::Commands::Version::VERSION
s.license = 'MIT'
s.summary = 'GitHub Issues command line interface'
s.description = <<EO... |
class AddOvertimeIn < ActiveRecord::Migration[5.1]
def change
change_column :timelogs, :break, :datetime
rename_column :timelogs, :break, :overtime_in
end
end
|
class Payload
pattr_initialize :unparsed_data
def data
@data ||= parse_data
end
def head_sha
pull_request.fetch('last_commit', {})['id']
end
def github_repo_id
pull_request['target_project_id']
end
def full_repo_name
repository['namespace'] + '/' + repository['name']
end
def pul... |
class Vigil
class RevisionRepository
def initialize(env, project)
@os = Vigil.os
@project = project
@env = env
end
def new
Revision.new(@env, most_recent_revision.id+1, @project)
end
def all
_entries.map {|id| Revision.new(@env, id, @project)}
end
... |
require 'active_support/core_ext'
module CloudConductorCli
module Models
describe Blueprint do
let(:blueprint) { CloudConductorCli::Models::Blueprint.new }
let(:commands) { CloudConductorCli::Models::Blueprint.commands }
let(:mock_blueprint) do
{
id: 1,
project_id: 1... |
# == Schema Information
#
# Table name: payments
#
# id :integer(4) not null, primary key
# invoice_id :integer(4)
# confirmation_id :string(255)
# amount :integer(4)
# error :string(255)
# error_code :string(255)
# message :string(255)
# action :s... |
require 'celluloid/autostart'
require 'status_sender'
class MyBackendProcess
include Celluloid
attr_reader :status
def initialize
@state = 'idle'
@sender = StatusSender.new(self)
end
def run
change_state('running')
report_completion_percent 0
report_status('run method invoked')
sle... |
module Screwed
JavaScriptSpecDirs = [
"examples/javascripts",
"spec/javascripts",
"test/javascript",
"test",
"tests",
"spec",
"specs"
]
def self.location
File.dirname(__FILE__)
end
def self.rhino_command
"java -Dscrewed.dir=\"#{location}\" -jar \"#{locatio... |
# frozen_string_literal: true
require_relative 'game'
# INITIAL PLAN:
# Game creates Board with 7x6 grid
# Game creates two Players with two different pieces ⚪⚫
# While the game is not over:
# Game sets the current player
# Board keeps asking current player for a move until it receives a valid move
# Board adds... |
# frozen_string_literal: true
require "rails_helper"
RSpec.describe "courses/show", type: :view do
let(:subject) { FactoryBot.create(:subject) }
let(:course) { FactoryBot.create(:course) }
before do
user = FactoryBot.create(:user)
sign_in user
end
it "renders attributes in <p>" do
assign(:subj... |
require 'rails_helper'
RSpec.describe Employee, type: :model do
let(:valid_attributes) {
(FactoryGirl.build :employee).attributes.symbolize_keys.select {|_, value| !value.nil? }
}
let!(:employee){ FactoryGirl.build(:employee) }
let!(:restaurant){ FactoryGirl.build(:restaurant)}
it "has a valid factor... |
# Source: https://launchschool.com/exercises/90d719d7
# Q: Create a simple tip calculator. The program should prompt for a bill amount
# and a tip rate. The program must compute the tip and then display both the tip
# and the total amount of the bill.
def prompt(message)
puts "=> #{message}"
end
prompt('How much w... |
class Profile < ApplicationRecord
enum sex: %i(male female maybe)
ATTRIBUTE_PARAMS = %i(name sex date_of_birth).freeze
belongs_to :user
validates :name, presence: true,
length: {maximum: Settings.user_model.name_maximun}
validates :sex, inclusion: {in: :sex}, allow_nil: true
validates :date_of_birth, ... |
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2018, OpenNebula Project, OpenNebula Systems #
# #
# Licensed under the Apache License, Version 2.0 (the "License... |
require 'salesforce_bulk_query/job'
require 'date'
module SalesforceBulkQuery
# Abstraction of a single user-given query. It contains multiple jobs, is tied to a specific connection
class Query
# if no date_to is given we use the current time with this offset
# subtracted (to make sure the freshest chang... |
class CreatePortals < ActiveRecord::Migration
def change
create_table :portals do |t|
t.integer :latE6,:null => false
t.integer :lngE6,:null => false
t.string :address,:null => false
t.string :name,:null => false
t.timestamps
end
add_index :portals, [:latE6, :lngE6], :uniqu... |
#!/usr/bin/env ruby
# Input: one word per line.
# Output: one word per line, split via Tex's hyphenation rules, duplicates removed.
# Extra output: dict_subwords.txt, one subword per line, duplicates removed.
#
# Hyphenates 250K words per minute.
# Splitting into subwords is much slower, 4K wpm. C++ would be better ... |
class SchoolyearsController < ApplicationController
before_action :set_schoolyear, only: [:show, :edit, :update, :destroy]
# GET /schoolyears
# GET /schoolyears.json
def index
@schoolyears = Schoolyear.all
end
# GET /schoolyears/1
# GET /schoolyears/1.json
def show
end
# GET /schoolyears/new
... |
require 'minitest'
require 'minitest/autorun'
require './lib/binary_tree_node'
class BinaryTreeNodeTest < Minitest::Test
def setup
@node5 = BinaryTreeNode.new(5)
node3 = @node5.insert_left(3)
node1 = node3.insert_left(1)
node4 = node3.insert_right(4)
node8 = @node5.insert_right(8)
node12 = n... |
class ListsController < ApplicationController
def index
@lists = List.all
@list = List.new
end
def create
@list = List.new(params[:list])
if @list.save
redirect_to list_path(@list)
else
flash[:error] = "failed to create list"
redirect_to root_path
end
end
def new
... |
class AnswerDetail < ActiveRecord::Base
attr_accessible :topic_id, :question_id, :activity_id, :answer, :comment
belongs_to :question
belongs_to :activity
scope :by_topic_id, lambda { |topic_id| where(topic_id: topic_id) }
end
|
class Comic < ApplicationRecord
COMIC_ATTR = %i(name author description thumb publish_date
views status category_id).freeze
has_many :relationships
has_many :likes, through: :relationships, source: :relationshipable,
source_type: :Like
has_many :following, through: :relation... |
class AddProductGroupToProduct < ActiveRecord::Migration[6.0]
def change
change_table :refinery_caststone_products, if_exists: true do |t|
t.column :product_group_id, :bigint, if_not_exists: true
end
end
end
|
require 'spec_helper'
module SonyCameraRemoteAPI
describe SonyCameraRemoteAPI::Camera, HDR_AZ1: true do
let(:cam) { @cam_rcn }
let(:http) { cam.instance_variable_get(:@http) }
let(:recon) { cam.instance_variable_get(:@retrying).instance_variable_get(:@reconnect_by) }
before :each do
FileUtils... |
#
# Cookbook Name:: consul-nodocker
# Recipe:: consul
#
# Greg Konradt. Dec 2016
bash 'set_hostname' do
user 'root'
cwd '/tmp'
code <<-EOH
echo consul-server > /etc/hostname
echo "#{node['ipaddress']} consul-server" >> /etc/hosts
hostname consul-server
EOH
end
package 'unzip' do
action :install... |
module Skore
module DB
module Enrollment
def create
db.execute <<-SQL
create table if not exists enrollments(
category_id integer, category_name varchar(200),
user_id integer, grade varchar(40), progress integer
created_at text, created_at_epoch integer
... |
Rails.application.routes.draw do
devise_for :users, path: '',
path_names: {sign_in: 'login', sign_up: 'signup'},
controllers: {sessions: 'devise/sessions'}
root to: "sandwich_views#index"
get 'users/:id', to: 'users#show'
resources :sandwiches, only: [:index, :show], controller: "sandwich_view... |
class BuildFeedWorker
include Sidekiq::Worker
def perform(post_id)
post = Post.find(post_id)
# add the post to the feed of this user
Feed.create!(user_id: post.user_id, post_id: post_id)
# find all of his followers and add this post to their feed
followers = Follower.where(user_id: post.user_id... |
require 'date'
class SeasonMatchGroup < Sequel::Model
plugin :validation_helpers
many_to_one :season
one_to_many :matches, :class => :Match, :key => :season_match_group_id
def validate
super
validates_presence [:name, :season_id]
validates_max_length 64, :name
validates_min_length 4, :name
v... |
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
module NapakalakiGame
require_relative "CardDealer.rb"
require_relative "CombatResult.rb"
require_relative "Player"
require "singleto... |
class Api::V1::ExpensesController < ApplicationController
# POST /expenses
def create
@expense = Expense.create!(expense_params)
json_response(@expense, :created)
end
private
def expense_params
# whitelist params
params.permit(:spent_for, :amount, :pricy)
end
end
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../models/shoos.rb')
class TestShoo < MiniTest::Test
def setup
options = {'first_name' => 'Bobby', 'last_name' => 'Dazzler', 'style' => 'Leather Swagger', 'size' => 8, 'quantity' => 4}
@shoo = Shoo.new(options)
end
def test_first_name... |
class AddWxInforToCardOrders < ActiveRecord::Migration
def change
add_column :card_orders, :wx_prepay_id, :string
add_column :card_orders, :wx_noncestr, :string
add_column :card_orders, :wx_transaction_id, :string
end
end
|
class CreateChannels < ActiveRecord::Migration
def change
create_table :channels do |t|
t.references :student_class
t.references :learning_track
t.timestamp
end
add_foreign_key :channels, :student_classes
add_foreign_key :channels, :learning_tracks
add_index :channels, [:student... |
class OrganizationShebaosController < ApplicationController
before_action :set_model_class
before_action :set_organization_shebao,
only: [:show, :edit, :update, :finish_apply_start,
:finish_apply_stop, :finish_apply_restart]
# GET /organization_shebaos
# GET /organiz... |
require "thumbnail_setter"
describe ThumbnailSetter do
let(:youtube_video) { stub(video_url: "http://www.youtube.com/watch?v=45203970",
video_id: "45203970") }
let(:vimeo_video) { stub(video_url: "http://www.vimeo.com/315604574",
video_id: "315604574"... |
###########################################################
#
# Name: Joseph Markley
# Assignment: Rock Paper Scissors
# Date: 01/29/2019
# Class: CIS 282
# Description: Rock Paper Scissors Game
#
####################################################... |
class Coda < Cask
url 'https://panic.com/coda/d/Coda%202.0.12.zip'
homepage 'https://panic.com/Coda/'
version '2.0.12'
sha1 '7157f0213edf39aca296c8bc4cb5a0e6f5ca6f75'
link 'Coda 2.app'
end
|
class AddLast4AmountSuccessAndAuthorizationcodeToOrders < ActiveRecord::Migration
def change
add_column :orders, :last4, :string
add_column :orders, :success, :boolean
add_column :orders, :authorization_code, :string
add_column :orders, :amount, :decimal
end
end
|
# return true to ignore or false to send
Honeybadger.exception_filter do |notice|
ActionDispatch::ExceptionWrapper.rescue_responses.keys.include? notice[:error_class]
end
|
module Kaya
module API
class Result
def self.get_for_suite(suite_id)
suite = Kaya::Suites::Suite.get(suite_id)
if suite
{
"project_name" => Dir.pwd.split("/").last,
"suite" => {id:suite.id, name:suite.name},
"results" => results_list_for(suite.id... |
#Hangman class
#jacob & kuhfß 2013
class Hangman
attr_writer :max_mistakes #number of mistakes the player can make
attr_reader :win #if the player wins the game @win becomes true
attr_reader :finished #indicates if the game has finished
attr_reader :player_word #string of _ and letters
def init... |
require_relative '../command_handler.rb'
require_relative '../galaxy_units_manager.rb'
require_relative '../galaxy_resources_manager.rb'
class CommandHandlers::AlienResourceDeclaration < CommandHandler
PATTERN = /^([a-z ]+)([A-Z]\w+) is (\d+) Credits$/ # Example: glob glob Silver is 34 Credits
class << self
d... |
class RenameKeyIdToAccessKeyIdInKeyedFolders < ActiveRecord::Migration
def self.up
rename_column :keyed_folders, :key_id, :access_key_id
end
def self.down
rename_column :keyed_folders, :access_key_id, :key_id
end
end
|
require 'time'
def odd_median(nums)
nums[nums.length / 2]
end
def sum_list(nums)
sum = 0
nums.each { |num| sum += num }
sum
end
def double_pointed_sum(nums)
sum = 0
(0..(nums.length / 2) - 1).each do |index|
mirror_index = -index - 1
sum += nums[index] + nums[mirror_index]
end
sum += odd_medi... |
module CollectionSpace
module Converter
module PublicArt
COMMON_ERA_URN = "urn:cspace:publicart.collectionspace.org:vocabularies:name(dateera):item:name(ce)'CE'"
class PublicArtCollectionObject < CollectionObject
def convert
run(wrapper: "document") do |xml|
xml.send(
... |
class TaskList < ActiveRecord::Base
belongs_to :store
has_many :completed_tasks
has_many :tasks, through: :completed_tasks
has_many :task_list_employees
has_many :employees, through: :task_list_employees
has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url =>... |
class User < ActiveRecord::Base
belongs_to :dispute
validates :dispute_id, presence: true
validates :name, uniqueness: { scope: :dispute_id }
validate :items_match_dispute_items
private
def items_match_dispute_items
errors.add(:items, "User is missing items!") if (dispute.items - items).any?
end
end
|
class AddFootballMatches < ActiveRecord::Migration
def up
create_table :football_matches do |t|
t.integer :home_team
t.integer :quest_team
t.integer :home_goals
t.integer :quest_goals
t.date :game_date
t.integer :tour
t.integer :league
t.timestamps
end
... |
class Order < ApplicationRecord
belongs_to :consultation
belongs_to :user
has_many :order_items
has_many :prescriptions, through: :order_items
monetize :total_cost_cents
end
|
require 'spec_helper'
describe Tincan::Sender do
let(:sender) { Tincan::Sender.new(options) }
let(:redis) { ::Redis.new(host: options[:redis_host]) }
let(:fixture) { IO.read('spec/fixtures/message.json').strip }
let(:message) { Tincan::Message.from_json(fixture) }
let(:options) do
{
redis_host: 'lo... |
class Forest::BaseController < ForestLiana::ApplicationController
protected
def resource_class
@resource_class ||= self.class.name.demodulize.gsub(/Controller$/, '').classify.constantize
end
def resources
@resources ||= resource_class.find(resource_ids)
end
def resource_ids
@r... |
class CreateStatuses < ActiveRecord::Migration[5.0]
def change
create_table :statuses do |t|
t.integer :book_id
t.integer :user_id
t.index [:book_id, :user_id]
t.index [:user_id, :book_id]
t.boolean :read, default: false
t.boolean :toRead, default: false
t.boolean :favorite... |
module CalculableAttrs::ActiveRecord::Querying
delegate :calculate_attrs, :includes_calculable_attrs, :joins_calculable_attrs, to: :all
end
|
require_relative 'spec_helper'
require_relative '../lib/Bluray'
describe Bluray do
before(:context) do
@bluray = Bluray.new "Bluray Name", 5.99
@bluray2 = Bluray.new "Some Title", 7.99, 2
end
#check inilization
describe "Initialize" do
it "Initialize Name" do
expect(@bluray.name).to eq("Bluray... |
class CartProductsController < ApplicationController
def create
@cart_product = CartProduct.new(cart_product_params)
@product = Product.find(params[:id])
@cart_product.product_id = @product.id
@cart_product.customer_id = current_customer.id
if @cart_product.save
redirect_to cart_products_pa... |
require 'test_helper'
class UndergraduatesControllerTest < ActionDispatch::IntegrationTest
setup do
@undergraduate = undergraduates(:one)
end
test "should get index" do
get undergraduates_url
assert_response :success
end
test "should get new" do
get new_undergraduate_url
assert_response... |
# Problem 58: Spiral primes
# http://projecteuler.net/problem=58
# Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
# 37 36 35 34 33 32 31
# 38 17 16 15 14 13 30
# 39 18 5 4 3 12 29
# 40 19 6 1 2 11 28
# 41 20 7 8 9 10 27
# 42 21 22 23 24 25 2643... |
require "test_helper"
describe WorksController do
# it "does a thing" do
# value(1+1).must_equal 2
# end
describe "fixtures verification" do
it "verifies that work fixtures are functional" do
expect(Work.count).must_equal 5
end
end
describe "new" do
it "responds with success beca... |
FactoryGirl.define do
factory :user do
email "test_user@test.com"
password_digest "password"
end
factory :post do
title "elves men hobbits dawrfs"
tag_list "Middle Earth"
content "middle earth rocks, Toklien was an amazing person "
end
end
|
# Documentation: https://github.com/Homebrew/brew/blob/master/share/doc/homebrew/Formula-Cookbook.md
# http://www.rubydoc.info/github/Homebrew/brew/master/Formula
# PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
class AndroidResourceFormatter < Formula
desc ""
homepage ""
... |
class PersonEmail < ActiveRecord::Base
belongs_to :person
after_create :send_email
validates_presence_of :sender_name, :sender_email, :message
def send_email
PersonMailer.public_contact(self).deliver
end
end
|
class AddSurnameToEmployees < ActiveRecord::Migration[6.1]
def change
add_column :employees, :suranme, :string
end
end
|
class Captain < ActiveRecord::Base
has_many :boats
has_many :classifications, through: :boats
def self.catamaran_operators
includes(:classifications).where('classifications.name = ?', 'Catamaran').references(:classifications)
end
def self.sailors
includes(:classifications).where('classifications.nam... |
class Condition < ActiveRecord::Base
belongs_to :conditionable, :polymorphic => :true
belongs_to :classification
module Scopes
def historical
where(:category => "historical")
end
def present
where(:category => "present")
end
end
extend Scopes
end
|
class RemoveTypeFromHairs < ActiveRecord::Migration
def change
remove_column :hairs, :type, :string
end
end
|
class CreateSendingDestinations < ActiveRecord::Migration[5.0]
def change
create_table :sending_destinations do |t|
t.string :destination_family_name, null: false
t.string :destination_first_name, null: false
t.string :destination_first_name_kana, null: false
t.string :dest... |
# Install a separate browser for FB
package "epiphany-browser" do
action :install
end
# Install a skeleton Facebook "application" for each user with user id between 1000 and 1099
node['etc']['passwd'].each do |user, data|
if data['uid'].to_i >= 1000 && data['uid'].to_i < 1100 then
directory "/home/#{user}/.g... |
class Item < ApplicationRecord
has_many :users, through: :purchases
belongs_to :category
has_many :purchases
belongs_to :brand, optional: true
has_many :likes, dependent: :destroy
#以下アソシエーションは今後の実装で必要な為、コメントアウトを残しています
# has_many :comments dependent: :destroy
# has_many :messages dependent: :destroy
ha... |
module CDI
module V1
class UserPreferenceSerializer < ActiveModel::Serializer
root false
attributes :id, :type, :title, :author, :link
def type
object.preference_type
end
end
end
end
|
module Categorizable
extend ActiveSupport::Concern
included do
has_many :category_resources, as: :resource
has_many :categories, through: :category_resources
validate :min_max_categories
end
def categories_names
categories.pluck(:name)
end
private
def min_max_categories
if cate... |
class RemoteThumbnail
attr_accessor :url, :width, :height
end |
class UsersController < ApplicationController
def index
if user_signed_in?
@users = current_user.all_following
end
end
def show
@user = current_user
@contact = @user.contact
end
def follow
@user = User.find(params[:id])
redirect_to(:back)
if current_user
if current_... |
class Event < ApplicationRecord
belongs_to :actor, counter_cache: true
belongs_to :repo
self.inheritance_column = :_type_disabled
accepts_nested_attributes_for :actor
accepts_nested_attributes_for :repo
end
|
Qiankun::Admin.controllers :room_families do
get :index do
@title = "Room_families"
@room_families = RoomFamily.all
render 'room_families/index'
end
get :new do
@title = pat(:new_title, :model => 'room_family')
@room_family = RoomFamily.new
render 'room_families/new'
end
post :create... |
module Robbie
module Parsers
class Search < BaseParser
class << self
def search(q)
response = query("/search/v2.1/music/search", {
query: q.gsub(/\s| |%20/, "+"),
entitytype: "artist&entitytype=album"
})
parse(response["searchResponse"]["results"... |
# frozen_string_literal: true
require "spec_helper"
module Decidim
module Opinions
describe Opinion do
subject { opinion }
let(:component) { build :opinion_component }
let(:organization) { component.participatory_space.organization }
let(:opinion) { create(:opinion, component: component... |
require 'time'
require 'date'
module Generatable
def alphabet
("a".."z").to_a << " "
end
def date_generator
Time.now.strftime("%d%m%y")
end
def key_generator
(0..99999).to_a.sample.to_s.rjust(5, "0")[0..4]
end
end
|
require 'resque'
require 'twitter'
require 'json'
require 'mysql2'
require File.join(File.dirname(__FILE__), '../models/name_gender.rb')
class DataObject
def initialize()
@db = Mysql2::Client.new(:host => "localhost", :username => "fbserver", :database=>"fbserver_development")
#@db = Mysql.new("localhost", ... |
# frozen_string_literal: true
module Bolt
class ApplyTarget
ATTRIBUTES = %i[uri name target_alias config vars facts features
plugin_hooks safe_name].freeze
COMPUTED = %i[host password port protocol user].freeze
attr_reader(*ATTRIBUTES)
attr_accessor(*COMPUTED)
# rubocop:disa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.