Generate a constants file by grabbing identifiers from storyboards in a project.

Related tags

Tools SBConstants
Overview

sbconstants

Generate a constants file by grabbing identifiers from storyboards in a project.

Installation

$ gem install sbconstants

Usage

For automated use:

  1. Add a file in Xcode to hold your constants e.g. PASStoryboardConstants.(h|m)
  2. Add a build script to build phases e.g. sbconstants path_to_constant_file
  3. Enjoy your identifiers being added as constants to your constants file

For manual use (using swift):

  1. Add a file in Xcode to hold your constants e.g. StoryboardIdentifiers.swift
  2. Add a command to your Makefile to run something similar to sbconstants path/to/StoryboardIdentifiers.swift --source-dir path/to/Storyboards --swift

Command line API

$ sbconstants -h
Usage: DESTINATION_FILE [options]
    -d, --dry-run                    Output to STDOUT
    -p, --prefix=<prefix>            Only match identifiers with <prefix>
    -i, --ignore=<files_to_ignore>   Comma separated list of files to ignore
    -s, --source-dir=<source>        Directory containing storyboards
    -t, --templates-dir=<templates>  Directory containing the templates to use for code formatting
    -q, --queries=<queries>          YAML file containing queries
    -v, --verbose                    Verbose output
    -w, --swift                      Output to a Swift File

An example usage would look like:

sbconstants MyApp/Constants/PASStoryboardConstants.h

NB The argument is the destination file to dump the constants into - this needs to be added manually

Every time sbconstants is run it will parse the storyboard files and pull out any constants and then dump them into PASStoryboardConstants.(h|m). This of course means that PASStoryboardConstants.(h|m) should not be edited by hand as it will just be clobbered any time we build.

The output of running this tool will look something like this:

PASStoryboardConstants.h

// Auto generated file - any changes will be lost

#import <Foundation/Foundation.h>

#pragma mark - segue.identifier
extern NSString * const PSBMasterToDetail;
extern NSString * const PSBMasterToSettings;

#pragma mark - storyboardNames
extern NSString * const Main;

#pragma mark - tableViewCell.reuseIdentifier
extern NSString * const PSBAwesomeCell;

PASStoryboardConstants.m

// Auto generated file - any changes will be lost

#import "PASStoryboardConstants.h"

#pragma mark - segue.identifier
NSString * const PSBMasterToDetail = @"PSBMasterToDetail";
NSString * const PSBMasterToSettings = @"PSBMasterToSettings";

#pragma mark - storyboardNames
NSString * const Main = @"Main";

#pragma mark - tableViewCell.reuseIdentifier
NSString * const PSBAwesomeCell = @"PSBAwesomeCell";

Using the --swift flag this would produce

// Auto generated file from SBConstants - any changes may be lost

public enum SegueIdentifier : String {
    case PSBMasterToDetail = "PSBMasterToDetail"
    case PSBMasterToSettings = "PSBMasterToSettings"
}

public enum StoryboardNames : String {
    case Main = "Main"
}

public enum TableViewCellreuseIdentifier : String {
    case PSBAwesomeCell = "PSBAwesomeCell"
}

The constants are grouped by where they were found in the storyboard xml e.g. segue.identifier. This can really help give you some context about where/what/when and why a constant exists.

##Options

Options are fun and there are a few to play with - most of these options are really only any good for debugging.

--prefix

-p, --prefix=
   
                Only match identifiers with 
    

    
   

Using the prefix option you can specify that you only want to grab identifiers that start with a certain prefix, which is always nice.

--ignore=

-i, --ignore=
   
       Comma separated list of files to ignore

   

Using the ignore option, you can specify files which will not be added to the generated constants file. If you need to ignore several files, you need to separate it with commas (-i MainStoryboard,HelpStoryboard,CellXIB).

--source-dir

-s, --source-dir=        Directory containing storyboards

If you don't want to run the tool from the root of your app for some reason you can specify the source directory to start searching for storyboard files. The search is recursive using a glob something like /**/*.storyboard

--dry-run

-d, --dry-run                    Output to STDOUT

If you just want to run the tool and not write the output to a file then this option will spit the result out to $stdout

--verbose

-v, --verbose                    Verbose output

Perhaps you want a little more context about where your identifiers are being grabbed from for debugging purposes. Never fear just use the --verbose switch and get output similar to:

sample output

// NSString * const FirstViewController = @"FirstViewController"; ">
#pragma mark - viewController.storyboardIdentifier
//
//    info: MainStoryboard[line:43](viewController.storyboardIdentifier)
// context: 
   
//
NSString * const FirstViewController = @"FirstViewController";

--queries

-q, --queries=
   
              YAML file containing queries

   

Chances are I've missed some identifiers to search for in the storyboard. You don't want to wait for the gem to be updated or have to fork it and fix it. Using this option you can provide a YAML file that contains a description of what identifers to search for. The current one looks something like this (NB this is a great starting point for creating your own yaml):

queries

---
segue: identifier
view: restorationIdentifier
? - tableViewCell
  - collectionViewCell
: - reuseIdentifier
? - navigationController
  - viewController
  - tableViewController
  - collectionViewController
: - storyboardIdentifier
  - restorationIdentifier

This looks a little funky but it's essentially groups of keys and values (both the key and the value can be an array). This actually gets expanded to the following table:

+--------------------------+-----------------------+
|         node             |      attribute        |
+ -------------------------+-----------------------+
| segue                    | identifier            |
| view                     | restorationIdentifier |
| tableViewCell            | reuseIdentifier       |
| collectionViewCell       | reuseIdentifier       |
| navigationController     | storyboardIdentifier  |
| viewController           | storyboardIdentifier  |
| tableViewController      | storyboardIdentifier  |
| collectionViewController | storyboardIdentifier  |
| viewController           | restorationIdentifier |
| navigationController     | restorationIdentifier |
| tableViewController      | restorationIdentifier |
| collectionViewController | restorationIdentifier |
+--------------------------+-----------------------+

--swift

-w, --swift                      Output to a Swift File

Outputs Swift code rather than Objective-C

--templates-dir

-t, --templates-dir=
   
      Directory containing the templates to use for code formatting

   

See below

Custom formatting

If you are running tools that verify your team is sticking to coding conventions you might find that the default output might not fit your requirements. Not to fear you can provide your own templates to decide the formatting you require by passing the --templates-dir option with the path to the directory containing the templates to use.

Inside your custom templates you can interpolate the constant_name and constant_value like this

<%= constant_value %>";">
NSString * const <%= constant_name %> = @"<%= constant_value %>";

You can override how the Objective-C constants are formatted by creating objc_header.erb and objc_implementation.erb files and adding the --templates-dir flag pointing to their containing directory.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request
Comments
  • @paulsamuels => Swift Support

    @paulsamuels => Swift Support

    I want to use this in artsy/eidolon but I want to keep it as swifty as possible.

    So I've added another flag to add support for outputting as swift and updated the README. You had a lot of training whitespace, so my editor cleaned those up as I was digging around in the source.

    When I tried to just run it from master I couldn't get the templates to run, so I made the head / body instance vars because I couldn't figure out how the data gets passed through. Good old ruby.

    Looks like this:

    // Auto generated file from SBConstants - any changes may be lost
    
    enum SegueIdentifier : String {
        case bid = "bid"
    }
    
    enum ViewControllerStoryboardIdentifier : String {
        case EnterYourBidDetails = "Enter Your Bid Details"
        case FulfillmentContainerViewController = "FulfillmentContainerViewController"
        case GetYourBidderDetails = "Get Your Bidder Details"
        case PlaceYourBid = "Place Your Bid"
        case SwipeCreditCard = "Swipe Credit Card"
    }
    

    random side-note, I also spent 2 years in the 3 years ago :)

    opened by orta 11
  • Fix #28 - add xib support

    Fix #28 - add xib support

    I'm not sure if this will cause any issue. I don't think it should be behind a feature switch as it seems like something that should just be default behaviour.

    @tp does this resolve your issue?

    opened by paulsamuels 10
  • Storyboard names

    Storyboard names

    I don't fully understand the template format yet, so I don't know if this only requires a template update.

    Could we include constants for the storyboard name? As used in + (UIStoryboard *)storyboardWithName:(NSString *)name bundle:(NSBundle *)storyboardBundleOrNil

    opened by Ashton-W 7
  • With rvm sbconstants doesn't run

    With rvm sbconstants doesn't run

    I have tried everything to make this part of my build phases with no luck. If I run this outside Xcode it works as expected; but running it like this will fail:

    sbconstants destinationFile.h
    

    This will fail with: sbconstants command not found.

    If I run it like this:

    `which sbconstants` destinationFile.h
    

    The build phase won't fail but no data will be generated to destinationFile.h.

    After reading your blog post you say it needs to be installed as "System Ruby" but since I have rvm in theory I don't have access to "System Ruby"; but running it with which should actually generate something (unless I'm missing something).

    I tried different options with no luck; even adding -v won't produce any output to the build phase.

    opened by esttorhe 6
  • Add support for different formatting for different nodes

    Add support for different formatting for different nodes

    Hi, is it possible to have custom formatting for the different nodes as well? Something like this for eg:

    pragma mark - segue.identifier

    NSString * const PSBMasterToDetail = @"PSBMasterToDetail-Segue"; NSString * const PSBMasterToSettings = @"PSBMasterToSettings-Segue";

    pragma mark - storyboardNames

    NSString * const Main = @"Main-Name";

    pragma mark - tableViewCell.reuseIdentifier

    NSString * const PSBAwesomeCell = @"PSBAwesomeCell-ReuseIdentifier";

    also, thanks for the awesome project!

    opened by mervynokm 5
  • Switching from enums to structs

    Switching from enums to structs

    Hi, I would like to suggest a change from enums to structs

    That way the resulting .swift file will be something like this, and will allow us to use them without calling .rawValue on each of them

    public struct SegueIdentifiers {
            static let AttachmentsScreen = "AttachmentsScreenSegue"
            static let TagsScreen = "TagsScreenSegue"
            static let TeamsScreen = "TeamsScreenSegue"
    }
    
    opened by raulriera 5
  • Unknown type name 'NSString' for objc code

    Unknown type name 'NSString' for objc code

    .../Source/Storyboard/StoryboardIdentifiers.m:3:9: In file included from error: unknown type name 'NSString' extern NSString * const SomeCell;

    There is no Foundation import for generated objc file. If I add id manual it works

    File Content

    // Auto generated file - any changes will be lost
    
    
    #pragma mark - tableViewCell.reuseIdentifier
    extern NSString * const SomeCell;
    
    opened by kostiakoval 5
  • Generate empty enum if section contains no constants

    Generate empty enum if section contains no constants

    I am using some helper methods and swift extensions to work with the enums provided by SBConstants. However, if e.g. there is no segue identifier setup in the storyboard, the generated SBConstants file omits the enum altogether.

    This of course breaks any custom code that directly references the enums, e.g. SegueIdentifier.

    I think it would be fine to output the empty enum in case there are no constants defined. Any opinions?

    opened by aschuch 5
  • Custom `objc_body.erb` template isn't used

    Custom `objc_body.erb` template isn't used

    The default template is always used for objc_body.

    See: https://github.com/paulsamuels/SBConstants/commit/0edae9903462c840783dea2bf03553f7ff818030#diff-a7b70ae59847e3f939f89777f94834c8R36

    opened by Ashton-W 4
  • Added option to remove space after '*' prior const declaration.

    Added option to remove space after '*' prior const declaration.

    This has been a pretty valuable tool for us; now not having to depend on manual addition of constants. However the generated code didn't match our coding standards and with Objective-Clean build phase in place we had to manually fix the code after generating it.

    I forked the gem and added an option that removes this space if the option is present; if not it will generate the code like you have it (keeping default behavior to avoid issues with people already using the gem).

    New option is -r and will produce constants like this:

    extern NSString *const HSGuidedFlow; // On the .h
    
    NSString *const HSGuidedFlow = @"HSGuidedFlow"; // On the .m
    

    Everything else is kept the same; the only change is now the ability to specify wether or not to have a space after the *. Don't know if this is valuable for anyone else but I figure if I was going to fork and add it I might as well make it available for you to judge if its worth merging.

    opened by esttorhe 4
  • Raw value missing in generated constant file.

    Raw value missing in generated constant file.

    Generated constant file doesn't contain raw String Value identifiers.

    example:

    public enum TableViewCellReuseIdentifier : String {
        case MessageCell
    }
    
    opened by mlvea 2
  • Convienience methods to utilize constants

    Convienience methods to utilize constants

    The code below is based on Reusable and uses the StoryboardNames generated to init VCs

    Storyboard Methods
    extension UIStoryboard {
    
        /// Convenience Initializers
        convenience init(storyboard: StoryboardNames, bundle: Bundle? = nil) {
    
            self.init(name: storyboard.rawValue, bundle: bundle)
        }
    
        /// Class Functions
        public static func storyboard(storyboard: StoryboardNames = .Main, bundle: Bundle? = nil) -> UIStoryboard {
    
            return UIStoryboard(name: storyboard.rawValue, bundle: bundle)
        }
    
        /// View Controller Instantiation from Generics
        func instantiateViewController<T: ViewControllerInitializer>(_: T.Type) -> T {
    
            guard let viewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T else {
                fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier) ")
            }
    
            return viewController
        }
    }
    

    Usage: let vc = UIStoryboard(storyboard: .Main)

    ViewController Methods
    extension UIViewController {
        
        public static func instantiateFromStoryboard(name storyboard: StoryboardNames = .Main) -> Self {
            
            func instantiateFromStoryboard<T: UIViewController>(_: T.Type) -> T {
                
                let sb = UIStoryboard(storyboard: storyboard)
                return sb.instantiateViewController(withIdentifier: String(describing: T.self)) as! T
            }
            
            return instantiateFromStoryboard(self)
        }
    }
    

    Usage: let vc = SearchViewController.instantiateFromStoryboard(name: .Main)

    I'm new to ruby or I'd make the PR myself, leaving the idea here if anyone does want to implement it.

    opened by multinerd 0
  • When a constant doesn’t match it’s sanitised form, output the quoted constant

    When a constant doesn’t match it’s sanitised form, output the quoted constant

    This PR fixes the issue raised in #52.

    This is useful when the storyboard file name on disk has spaces or other characters that are stripped by the string sanitiser.

    Before the changes introduced in this PR:

    public enum StoryboardNames: String {
        case ConstantsProperties
        case DebugLog // filename is actually "Debug Log.storyboard"
        case DocumentProperties   
    }
    

    After the changes introduced in this PR:

    public enum StoryboardNames: String {
        case ConstantsProperties
        case DebugLog = "Debug Log"
        case DocumentProperties
    }
    
    opened by tonyarnold 1
  • Scan for AppKit collectionViewItems

    Scan for AppKit collectionViewItems

    I'm not sure if the existing collectionViewController in identifiers.yml is the version for iOS, but in macOS projects, collection views are stored in collectionViewItem XML nodes in the Storyboard.

    I've added support for both collectionViewItems, tableColumn and tableCellView.

    This PR adds these items to the identifiers list.

    opened by tonyarnold 0
  • Add file name if it doesn't match the tokenised version

    Add file name if it doesn't match the tokenised version

    I've noticed that when sbconstants encounters a file with spaces in the name, it tokenises it to strip whitespace, like so:

    New Document.storyboardStoryboardNames.NewDocument

    That's great, but it results in an unusable enum entry. It would be great if this were handled automatically, i.e.:

    public enum StoryboardNames: String {
        case NewDocument = "New Document"
    }
    
    opened by tonyarnold 0
  • Enum naming convention

    Enum naming convention

    Currently sbconstants creates the enums in the format below public enum SegueIdentifier : String Most of the patterns and styleguides, and even Apple sample code recommend the format as below (no space between name and column) public enum SegueIdentifier: String Considering this is more of a stylistic and opinionated change, would it make sense to update swift_body.erb to match the common conventions? I can create a PR if so.

    I know the templates directory parameter solves it for any tweaks users need, but I am guessing there would be a lot who prefer it without the extra space, because the rest of the lines do follow common convention - so this comment

    opened by deepumukundan 1
Owner
paul.s
paul.s
Xcode storyboards diff and merge tool.

StoryboardMerge Storyboard diff and merge tool which: compares and merges two storyboard files, provides an automatic merge-facility, The storyboardin

null 238 Sep 12, 2022
SwiftGen is a tool to automatically generate Swift code for resources of your projects

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

null 8.3k Jan 5, 2023
This repository contains rules for Bazel that can be used to generate Xcode projects

rules_xcodeproj This repository contains rules for Bazel that can be used to generate Xcode projects. If you run into any problems with these rules, p

BuildBuddy 233 Dec 28, 2022
automatically delete the current project's DerivedData directories

Feature automatically delete the current project's DerivedData directories Usage It will be automatically deleted DerivedData when you run the clean I

Toshihiro Morimoto 242 Dec 16, 2022
An executable that can be called from a Run Script Build Phase that makes comments such as // TODO: or // SERIOUS: appear in Xcode's Issue Navigator giving them project-wide visibility.

XcodeIssueGenerator An executable that can be called from a Run Script Build Phase that makes comments such as // TODO: or // SERIOUS: appear in Xcode

Wunderman Thompson Apps 143 Oct 11, 2022
It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.

Link Previewer for iOS, macOS, watchOS and tvOS It makes a preview from an URL, grabbing all the information such as title, relevant texts and images.

Leonardo Cardoso 1.3k Jan 2, 2023
Swift Programming Basics - Collections, Variables & Constants

Dicee What I learned in this module How to clone an existing Xcode project from GitHub. Create an app with behaviour and functionality. Create links b

null 0 Jan 9, 2022
Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri

Capacitor File Opener. The plugin is able to open a file given the mimeType and the file uri. This plugin is similar to cordova-plugin-file-opener2 without installation support.

Capacitor Community 32 Dec 21, 2022
A common use case is wanting to convert device identifiers such as iPhone10,1 to a user friendly name; iPhone 8.

Devices Swift package that contains all devices from https://www.theiphonewiki.com/wiki/Models. A common use case is wanting to convert device identif

null 17 Nov 28, 2022
MacLookup - Lookup for all Mac names, colors, model identifiers and part numbers

MacLookup Lookup for all Mac names, colors, model identifiers and part numbers.

Voyager Software Inc. 2 Jan 4, 2022
Thomas Grapperon 32 Dec 12, 2022
Store values using unique, randomly generated identifiers

Storage Store values using unique, randomly generated identifiers. This packages consists of three types: A Storage class, a UniqueIdentifiable protoc

Jordan Baird 1 Feb 23, 2022
A command line tool to parse pricing from a pdf and generate an updated csv file for House Call Pro

A command line tool to parse pricing from a pdf and generate an updated csv file for House Call Pro

hhe-dev 10 Feb 17, 2022
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

null 8.3k Dec 31, 2022
Localize is a framework writed in swift to localize your projects easier improves i18n, including storyboards and strings.

Localize Localize is a framework written in swift to help you localize and pluralize your projects. It supports both storyboards and strings. Features

Andres Silva 279 Dec 24, 2022
Super lightweight library that helps you to localize strings, even directly in storyboards!

Translatio Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 9 or higher. Swi

Andrea Mario Lufino 19 Jan 29, 2022
Custom segue for OSX Storyboards with slide and cross fade effects (NSViewControllerTransitionOptions)

CustomSegue Custom segue for OSX Storyboards. Slide and cross fade effects, new customized window. class MyViewController: NSViewController { overr

Eric Marchand 123 May 21, 2022
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

null 8.3k Jan 3, 2023
Play with Xcode storyboards...

Storyboards In this repo, we will be playing with storyboards. Add Table View and Collection Views and show some data using the data source and delega

null 0 Oct 14, 2021
A Swift mixin for reusing views easily and in a type-safe way (UITableViewCells, UICollectionViewCells, custom UIViews, ViewControllers, Storyboards…)

Reusable A Swift mixin to use UITableViewCells, UICollectionViewCells and UIViewControllers in a type-safe way, without the need to manipulate their S

Olivier Halligon 2.9k Jan 3, 2023