Xcodeproj add custom property to object - ruby

I want to add onlyGenerateCoverageForSpecifiedTargets property to TestAction object programmatically. According to the documentation this property is not yet supported. So I need to add a custom property to an object. Also I need to add CodeCoverageTargets group.
Here is my code:
scheme = Xcodeproj::XCScheme.new
scheme.add_build_target(app_target)
scheme.set_launch_target(app_target)
scheme.add_test_target(target)
test_action = scheme.test_action
test_action.code_coverage_enabled = true
# add onlyGenerateCoverageForSpecifiedTargets = true
scheme.test_action = test_action
scheme.save_as(xcode_proj_dir, name)
Here is xml structure when I add property from Xcode GUI.
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
codeCoverageEnabled = "YES"
onlyGenerateCoverageForSpecifiedTargets = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D7CE66BC1C7DE6F700FC64CC"
BuildableName = "AppName.app"
BlueprintName = "AppName"
ReferencedContainer = "container:buddyui.xcodeproj">
</BuildableReference>
</MacroExpansion>
<CodeCoverageTargets>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D7CE66BC1C7DE6F700FC64CC"
BuildableName = "AppName.app"
BlueprintName = "AppName"
ReferencedContainer = "container:buddyui.xcodeproj">
</BuildableReference>
</CodeCoverageTargets>

I'll say it first: I know nothing about the Xcodeproj Gem nor the logic behind Xcode metadata. Take my code as a starter for further improvements.
You have a few ways of achieving what you asked:
MonkeyPatch Xcodeproj. That is what I did, sorry for that :-P
Extend Xcodeproj classes. That would be the recommended solution.
Manipulate the XML file or the XCScheme object directly, with REXML.
Here comes my proposal. I added a few methods to TestAction (based on the code of similar existing methods) and created the additional class CodeCoverageTargets (based on the class MacroExpansion). As I don't know how Xcode works, I chose to create the method add_code_coverage_targets in XCScheme instead of overwriting set_launch_target (where MacroExpansion is instantiated).
require 'xcodeproj'
class Xcodeproj::XCScheme
def add_code_coverage_targets(build_target)
code_cov_targets = CodeCoverageTargets.new(build_target)
test_action.add_code_coverage_targets(code_cov_targets)
end
class CodeCoverageTargets < XMLElementWrapper
def initialize(target_or_node = nil)
create_xml_element_with_fallback(target_or_node, 'CodeCoverageTargets') do
self.buildable_reference = BuildableReference.new(target_or_node) if target_or_node
end
end
def buildable_reference
#buildable_reference ||= BuildableReference.new #xml_element.elements['BuildableReference']
end
def buildable_reference=(ref)
#xml_element.delete_element('BuildableReference')
#xml_element.add_element(ref.xml_element)
#buildable_reference = ref
end
end
class TestAction
def only_generate_coverage_for_specified_targets?
string_to_bool(#xml_element.attributes['onlyGenerateCoverageForSpecifiedTargets'])
end
def only_generate_coverage_for_specified_targets=(flag)
#xml_element.attributes['onlyGenerateCoverageForSpecifiedTargets'] = bool_to_string(flag)
end
def code_coverage_targets
#xml_element.get_elements('CodeCoverageTargets').map do |node|
CodeCoverageTargets.new(node)
end
end
def add_code_coverage_targets(code_coverage_targets)
#xml_element.add_element(code_coverage_targets.xml_element)
end
end
end
You can use it like this:
xcode_proj_dir = 'Desktop/SO/66719313/DummyApp.xcodeproj'
xcode_proj = Xcodeproj::Project.open(xcode_proj_dir)
app_target = xcode_proj.targets.first
scheme = Xcodeproj::XCScheme.new
scheme.add_build_target(app_target)
scheme.set_launch_target(app_target)
#scheme.add_test_target(app_target)
scheme.add_code_coverage_targets(app_target) # new method
test_action = scheme.test_action
test_action.code_coverage_enabled = true
test_action.only_generate_coverage_for_specified_targets = true # new method
puts test_action

You can simply create a module which adds the behaviour you want (i.e. your method), but I'm not sure this will fix your real problem
module AddOnlyGenerateCoverageForSpecifiedTargets
attr_accessor :only_generate_coverage_for_specified_targets
end
Then include the module in the class you want it. To include it in one object only, include it in its singleton_class:
test_action.singleton_class.include AddOnlyGenerateCoverageForSpecifiedTargets
# Now you can use it
test_action.only_generate_coverage_for_specified_targets = true

Related

Ruby iterating in a class method while referencing another class

Solved. I didn't have the initialization right, which gave the noMethodError. Then I was changing an array, but checking a variable that referred to a position in the array, and that variable had not been reassigned.
Edited to initialize bookPagesInfo, bookChaptersInfo, editPagesInfo, and editChapterInfo as suggested. Still gives the same NoMethod Error.
I have a book with page and chapter info, and want to be able to apply edits that change the number of pages, introPages, chapters, and povs.
class Book
attr_accessor :pages, :chapters, :bookPagesInfo, :bookChaptersInfo, :introPages, :povs
def initialize(bookPagesInfo, bookChaptersInfo)
#bookPagesInfo = bookPagesInfo
#bookChaptersInfo = bookChaptersInfo
#pages = bookPagesInfo[0]
#introPages = bookPagesInfo[1]
#chapters = bookChaptersInfo[0]
#povs = bookChaptersInfo[1]
end
def applyEdit(edit)
#pages += edit.new_pages
end
end
class Edit
attr_accessor :new_pages, :new_chapters, :editPagesInfo, :editChaptersInfo, :new_intro_pages, :new_povs
def initialize(editPagesInfo, editChaptersInfo)
#editPagesInfo = editPagesInfo
#editChaptersInfo = editChaptersInfo
#new_pages = editPagesInfo[0]
#new_intro_pages = editPagesInfo[1]
#new_chapters = editChaptersInfo[0]
#new_povs = editChaptersInfo[1]
end
end
The above code works for editing just number of pages. However, if I change my applyEdit method to iterate over the bookPagesInfo array, I can't get it to work. Running applyEdit below gives a nonfatal error.
def applyEdit(edit)
#bookPagesInfo.each_with_index do {|stat, idx| stat += edit.bookPagesInfo[idx]}
end
## gives undefined method `each_with_index' for nil:NilClass (NoMethodError), but
## my understanding is as long as bookPagesInfo was initialized as an array, it
## should be an array, not nilClass
I'm pretty new to classes (and this website, sorry for formatting). Thanks for the help.
You've got attr_accessors defined for :bookPagesInfo and :bookChaptersInfo, which will give you reader and writer methods, but it won't set #bookPagesInfo and #bookChaptersInfo for you in the initialize method - you need to do that yourself. So, when you try to read from the instance variable in applyEdit, you're reading nil.
Try adding
#bookPagesInfo = bookPagesInfo
#bookChaptersInfo = bookChaptersInfo
in Book#initialize.

Capybara.page not in scope after extending capybara-screenshot's after_failed_example method

I'm trying to override the after_failed_example method so I can inflict some custom file naming on our screenshots. I'm loading the module as an initializer.
So far, so good, but the Capybara.page.current_url is blank, making me think I need to require something additional?
require "capybara-screenshot/rspec"
module Capybara
module Screenshot
module RSpec
class << self
attr_accessor :use_description_as_filename
attr_accessor :save_html_file
end
self.use_description_as_filename = true
self.save_html_file = true
def self.after_failed_example(example)
if example.example_group.include?(Capybara::DSL) # Capybara DSL method has been included for a feature we can snapshot
Capybara.using_session(Capybara::Screenshot.final_session_name) do
puts ">>>> Capybara.page.current_url: " + Capybara.page.current_url.to_s
if Capybara::Screenshot.autosave_on_failure && failed?(example) && Capybara.page.current_url != ''
saver = Capybara::Screenshot.new_saver(Capybara, Capybara.page, Capybara::Screenshot.save_html_file?, set_saver_filename_prefix(example))
saver.save
example.metadata[:screenshot] = {}
example.metadata[:screenshot][:html] = saver.html_path if saver.html_saved?
example.metadata[:screenshot][:image] = saver.screenshot_path if saver.screenshot_saved?
end
end
end
private
def self.set_saver_filename_prefix(example)
return example.description.to_s.gsub(" ", "-") if Capybara::Screenshot.use_description_as_filename?
return Capybara::Screenshot.filename_prefix_for(:rspec, example)
end
end
end
end
end
This is successfully overriding the capybara-screenshot/rspec method, and any of the Capybara::Screenshot static information is accessible, but not Capybara session related information (afa I can tell).
For example, Capybara.page.current_url.to_s is null when overridden, but present when not.
I was missing a require (kind of silly mistake):
require 'capybara/rspec'

ruby clone an object

I need to clone an existing object and change that cloned object.
The problem is that my changes change original object.
Here's the code:
require "httparty"
class Http
attr_accessor :options
attr_accessor :rescue_response
include HTTParty
def initialize(options)
options[:path] = '/' if options[:path].nil? == true
options[:verify] = false
self.options = options
self.rescue_response = {
:code => 500
}
end
def get
self.class.get(self.options[:path], self.options)
end
def post
self.class.post(self.options[:path], self.options)
end
def put
self.class.put(self.options[:path], self.options)
end
def delete
self.class.put(self.options[:path], self.options)
end
end
Scenario:
test = Http.new({})
test2 = test
test2.options[:path] = "www"
p test2
p test
Output:
#<Http:0x00007fbc958c5bc8 #options={:path=>"www", :verify=>false}, #rescue_response={:code=>500}>
#<Http:0x00007fbc958c5bc8 #options={:path=>"www", :verify=>false}, #rescue_response={:code=>500}>
Is there a way to fix this?
You don't even need to clone here, you just need to make a new instance.
Right here:
test = Http.new({})
test2 = test
you don't have two instances of Http, you have one. You just have two variables pointing to the same instance.
You could instead change it to this, and you wouldn't have the problem.
test = Http.new({})
test2 = Http.new({})
If, however, you used a shared options argument, that's where you'd encounter an issue:
options = { path: nil }
test = Http.new(options)
# options has been mutated, which may be undesirable
puts options[:path] # => "/"
To avoid this "side effect", you could change the initialize method to use a clone of the options:
def initialize(options)
options = options.clone
# ... do other stuff
end
You could also make use of the splat operator, which is a little more cryptic but possibly more idiomatic:
def initialize(**options)
# do stuff with options, no need to clone
end
You would then call the constructor like so:
options = { path: nil }
test = Http.new(**options)
puts test.options[:path] # => "/"
# the original hasn't been mutated
puts options[:path] # => nil
You want .clone or perhaps .dup
test2 = test.clone
But depending on your purposes, but in this case, you probably want .clone
see What's the difference between Ruby's dup and clone methods?
The main difference is that .clone also copies the objects singleton methods and frozen state.
On a side note, you can also change
options[:path] = '/' if options[:path].nil? # you don't need "== true"

bad char after creating a Database from csv

I am trying to create a database using mongoid but it fails to find the create method. I am trying to create 2 databases based on csv files:
extract_data class:
class ExtractData
include Mongoid::Document
include Mongoid::Timestamps
def self.create_all_databases
#cbsa2msa = DbForCsv.import!('./share/private/csv/cbsa_to_msa.csv')
#zip2cbsa = DbForCsv.import!('./share/private/csv/zip_to_cbsa.csv')
end
def self.show_all_database
ap #cbsa2msa.all.to_a
ap #zip2cbsa.all.to_a
end
end
the class DbForCSV works as below:
class DbForCsv
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Attributes::Dynamic
def self.import!(file_path)
columns = []
instances = []
CSV.foreach(file_path, encoding: 'iso-8859-1:UTF-8') do |row|
if columns.empty?
# We dont want attributes with whitespaces
columns = row.collect { |c| c.downcase.gsub(' ', '_') }
next
end
instances << create!(build_attributes(row, columns))
end
instances
end
private
def self.build_attributes(row, columns)
attrs = {}
columns.each_with_index do |column, index|
attrs[column] = row[index]
end
ap attrs
attrs
end
end
I am not aware of all fields and it may change in time. that's why I have create database and generic mehtods.
I have also another issue after having fixed the 'create!' issue.
I am using the encoding to make sure only UTF8 char are handled but I still see:
{
"zip" => "71964",
"cbsa" => "31680",
"res_ratio" => "0.086511098",
"bus_ratio" => "0.012048193",
"oth_ratio" => "0.000000000",
"tot_ratio" => "0.082435345"
}
when doing 'ap attrs' in the code. how to make sure that 'zip' -> 'zip'
Thanks
create! is a class method but you're trying to call it as an instance method. Your import! method shouldn't be an instance method either, it should be a class method since it produces instances of your class:
def self.import!(file_path)
#-^^^^
# everything else would be the same...
end
You'd also make build_attributes a class method since it is just a helper method for another class method:
def self.build_attributes
#...
end
And then you don't need that odd looking new call when using import!:
def self.create_all_databases
#cbsa2msa = DbForCsv.import!('./share/private/csv/cbsa_to_msa.csv')
#zip2cbsa = DbForCsv.import!('./share/private/csv/zip_to_cbsa.csv')
end

Trying to access a variable inside a block

I'm trying to make a simple rss generator. My initialize method works fine and the update method runs without an error too but the new item in the update method never get added to the rss feed. I think it has something to do with how i'm accessing the variable 'maker' but i'm not sure.
require "rss"
class RSS_Engine
def initialize
#rss = RSS::Maker.make("atom") do |maker|
maker.channel.author = "Jamie"
maker.channel.updated = Time.now.to_s
maker.channel.about = "http://www.ruby-lang.org/en/feeds/news.rss"
maker.channel.title = "Example Feed"
#maker = maker
end
end
def update
#maker.items.new_item do |item|
item.title = "Test"
item.updated = Time.now.to_s
end
end
def print_rss
puts #rss
end
end
rss = RSS_Engine.new
rss.update
rss.print_rss
I got the original code from this example:
rss = RSS::Maker.make("atom") do |maker|
maker.channel.author = "matz"
maker.channel.updated = Time.now.to_s
maker.channel.about = "http://www.ruby-lang.org/en/feeds/news.rss"
maker.channel.title = "Example Feed"
maker.items.new_item do |item|
item.link = "http://www.ruby-lang.org/en/news/2010/12/25/ruby-1-9-2-p136-is-released/"
item.title = "Ruby 1.9.2-p136 is released"
item.updated = Time.now.to_s
end
This code works fine but i want to be able to add new posts to the rss feed over time so i'm trying to put the 'new.item' bit into it's own method.
The problem is not #maker variable, you have to invoke to_feed method to regenerate the feed after you modify it out of the code block.
So you need to add #rss = #maker.to_feed at the end of your update method.
One more thing about creating a new feed entry, link or id attribute need to be set.
Below code will work for you:
def update
#maker.items.new_item do |item|
item.link = "http://test.com"
item.title = "Test"
item.updated = Time.now.to_s
end
#rss = #maker.to_feed
end
If you are interested about why, you can take a look ruby rss source code. And below code(under rss/maker/base.rb) is the root cause why you need to invoke to_feed method if you modify feed out of the block:
def make(*args, &block)
new(*args).make(&block)
end
def make
yield(self)
to_feed
end

Resources